Question

I have a buffer reader working to read a text file then save the read data as a string. The buffer reader is in a continuous loop reading the text file every second. I would like to do a Thread.sleep if the buffer reader reads the same text two times in a row.

For example if the buffer reader reads "foo" then when it is ran again in the next second if it reads "foo" again then the thread sleeps for a certain amount of time.

I have the buffer reader within a try method but I do not know how to get it to do the above.

Could anyone help with this?

Thanks

Was it helpful?

Solution

Keep track of the previous line read in in a String variable, which you can initialize as an empty string. When you read in each line, check whether it's equals() to the previously stored line in that variable. If so, do what you want to do, like Thread.sleep(). Otherwise save the current line into that variable. In code:

    BufferedReader reader = new BufferedReader(new FileReader("foo.txt"));
    String foo = "";
    String old = "";
    while((foo = reader.readLine()) != null) {
        if(foo.equals(old)) {
            System.out.println("Sleeping...");
            Thread.sleep(1000);
        } else {
            old = foo;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top