2

I am trying to stream lines from a file using Java and for that I NEED to use scanner as it allows me to provide my own Delimiter Pattern. Now, the problem is, after reading through the file (in a java thread), and the scanner is still open, I am trying to read the new lines entered in the file by another process (like Continuous stream). I can do this successfully with Buffered Reader but unfortunately, I cannot provide my delimiter to this Reader. so, I have to use Scanner but it is not reading these new lines in the file. Is there anyway I can make scanner read through (or refresh and get) these new lines? I don't want to read from the beginning again .I am showing the sample code here to explain clearly:

    while (loopContinue)   // Always true so this thread will be open for             ever to keep reading this file for new messages
        {
            if(scanner.hasNext())  
            {

            String line=scanner.next();
                System.out.println(line);
            }
            else
            {
                Thread.sleep(10000);

            }
        }
        scanner.close();

Any help you can provide is appreciated. Thanks

kenny
  • 33
  • 2
  • I don't think this'll work well, but what if you refreshed the Scanner variable or initialized it again? – FailingCoder Mar 23 '19 at 03:28
  • 4
    Use `BufferedReader` to read the next line and then use `Scanner` to parse it – MadProgrammer Mar 23 '19 at 03:28
  • Thank you MadProgrammer for your suggestion. However, I cannot use BufferedReader as it breaks each line with newline "\r\n" (on windows) and I should use a different delimiter and not default "newline". Hope this helps understand my issue – kenny Mar 24 '19 at 02:34
  • @failingcoder: If I refresh scanner or re-initialize it, it will start from the first line of the file ..don't want that. Any other ideas? Thx. – kenny Mar 24 '19 at 03:59
  • Oops https://stackoverflow.com/questions/4149/how-do-i-use-java-to-read-from-a-file-that-is-actively-being-written-to this isn't really an exact duplicate though, because you are trying to use `java.util.Scanner` instead of other Buffered things. – FailingCoder Mar 24 '19 at 15:58

0 Answers0