问题描述
我对Java很陌生。我正在从URL中读取输入,该URL为我提供了实时的文本流。我想不断地将它写入一个文本文件,所以每次URL给出一个新的字符串我都把它添加到一个字符串缓冲区,在我的无限循环之外我把缓冲区的内容写到我的文件中。麻烦的是,我需要一种退出while循环的方法,因为服务器永远不会停止向我提供数据,所以我想做一些事情,比如在控制台中输入0以退出while循环并将内容写入文件。在那个问题上,有人知道我的StringBuffer类的对象是否会达到存储限制吗?
I'm pretty new to Java. I'm currently reading input from a URL which provides me with a real-time stream of text. I want to continually write this to a text file, so every time the URL gives a new string I add this to a string buffer, outside of my infinite while loop I write the contents of the buffer to my file. The trouble is, I need a way of exiting the while loop because the server never stops giving me data, so I want to do something such as enter 0 in the console to exit the while loop and write the contents to a file. On that subject, does anybody know if my object of the StringBuffer class will reach a storage limit?
推荐答案
循环不应该写到内存缓冲区,但直接到文件编写器(包装在BufferedWriter中)。这样可以避免内存不足。
The loop should not write to an in-memory buffer, but to the file writer directly (wrapped inside a BufferedWriter). This will avoid running out of memory.
你应该启动一个执行你的while循环的新线程,并在每次迭代时测试是否要求线程自行中断,使用 Thread.currentThread()。isInterrupted()
。一旦中断,线程应该停止while循环,并关闭writer。
You should start a new thread which executes your while loop, and tests at each iteration if the thread has been asked to interrupt itself, using Thread.currentThread().isInterrupted()
. Once interrupted, the thread should stop the while loop, and close the writer.
从命令行读取主线程,并在输入stop命令时调用编写器线程上的 interrupt()
。
Have your main thread read from the command line, and when the stop command is entered, call interrupt()
on the writer thread.
这篇关于如何通过某些用户输入退出连续的while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!