How do I exit a continuous while loop by some user

2019-09-21 22:36发布

问题:

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?

回答1:

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.

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.

Have your main thread read from the command line, and when the stop command is entered, call interrupt() on the writer thread.



回答2:

When you bring "Infinity" into picture, YES things are going to run out of memory at some point.

To exit a loop, you can have it running in a separate thread and let the main thread listen to the user inputs. And based on the input, the main thread will alter a shared variable, usually a boolean to determine an end.



回答3:

Using the break; statmement, you can break out of the most inner loop. I would suggest to create a boolean field called running. Each iteration of the loop, check it. If false, quit the loop.

Or even more efficient would be using the boolean as while-condition:

/* Declaration */
public volatile boolean running = true;

/* Code */
running = true;
while (running)
{


}

Based on user-input, put the running flag on false.

You could try something like this to make the flag turn to false when you type something in the console:

new Thread("User Input Handler", new Runnable()
{
    public void run()
    {
        try
        {
            System.in.read();
            running = false;
        } catch (Exception e) {}
    }
}).start();


回答4:

You can use the break; statement to jump out of the loop. What you'll need to do is check the input that you've read in against whatever you want your stopping condition to be, and if they match up then call break;. Something like this:

while(true) {
    String input = /* read input */;
    if("0".equals(input)
        break;
    /* whatever you want to do if you haven't hit your stopping condition */
}


标签: java io