简体   繁体   English

如何将字符串保存在本地缓冲区中,以便扫描程序可以重新读取它?

[英]How to save a String in local buffer so that it can be re-read by Scanner?

I am working on some project which deals with HTML pages. 我正在从事一些处理HTML页面的项目。 I don't want to download the same page over and over again, so I want to save it locally. 我不想一遍又一遍地下载同一页面,所以我想将其保存在本地。 I use the Scanner a lot, however the Scanner need a InputStreamReader . Scanner使用Scanner ,但是Scanner需要一个InputStreamReader For now I managed to save the HTML page to a local StringBuffer , however I can't make this StringBuffer be used with the Scanner . 现在我设法将HTML页面保存到本地的StringBuffer ,但是我不能使这个StringBufferScanner一起使用。

Can I make this StringBuffer be used as an InputStreamReader ? 我可以将此StringBuffer用作InputStreamReader吗? If not, then what method can I use? 如果没有,那我可以使用什么方法?

Scanner has a constructor taking a Readable . Scanner有一个采用Readable构造函数 Of all Readable implementations, the CharBuffer seems to suit your purpose the most since you want to have a readable and writeable source. 在所有Readable实现中, CharBuffer似乎最适合您的目的,因为您希望拥有一个可读可写的源。

String string = getItSomehow();
CharBuffer buffer = CharBuffer.wrap(string);
// ...
Scanner scanner = new Scanner(buffer);
// ...

Perhaps something along the lines of: 也许是这样的:

new InputStreamReader(new ByteArrayInputStream(new StringBuffer().toString().getBytes()));

If you want to do this right, you should send the HTTP GET request anyway, using the If-Modified-Since header, in order to correctly detect a page that has been changed. 如果要正确执行此操作,则无论如何都应使用If-Modified-Since标头发送HTTP GET请求,以便正确检测已更改的页面。

Have you considered using a proper HTTP proxy though? 您是否考虑过使用适当的HTTP代理? That would save you the hassle of re-inventing the wheel in your application. 这样可以避免您在应用程序中重新发明轮子的麻烦。 An HTTP proxy would probably perform better and it would be usable by more than a single application. HTTP代理的性能可能更好,并且可以被多个应用程序使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串中的新行字符插入PrintStream,然后使用扫描程序重新读取该文件 - how to insert a new line character in a string to PrintStream then use a scanner to re-read the file Kafka与Java:如何重新读取数据 - Kafka with Java: how to re-read data 如何读取文件内容,写入outputstream以及重新读取并存储在Java内存中的字符串变量中 - how to read contents of file, write to outputstream and the re-read and Store in a string variable in memory in java 内容更改后如何重新读取文本文件的新内容? - How can I re-read the new contents of a text file after the contents have changed? 如何创建一个休眠集合,每次我请求时都将重新读取它? - How can I create a hibernate collection that will be re-read every time I request it? 如何强制Android重新读取GPS位置? - How enforce Android to re-read GPS position? 如何重置偏移值重新读取kafka主题 - How to reset the offset value to re-read the kafka topic 调用IOUtils.copy后如何重新读取InputStream? - How to re-read an InputStream after calling IOUtils.copy? 无需重启即可重新读取配置 - Re-read configuration without restart FutureTask 实现重新读取 state 以防止泄漏中断 - FutureTask Implementation re-read state to prevent leaked intterupts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM