Java scanner will not follow the file

Trying to tail / parse some log files. Entries starting with a date can span many lines.

This works, but never sees new entries for the file.

File inputFile = new File("C:/test.txt"); InputStream is = new FileInputStream(inputFile); InputStream bis = new BufferedInputStream(is); //bis.skip(inputFile.length()); Scanner src = new Scanner(bis); src.useDelimiter("\n2010-05-01 "); while (true) { while(src.hasNext()){ System.out.println("[ " + src.next() + " ]"); } } 

It doesn't look like the next () or hasNext () scanner is detecting new entries in the file.

Any idea how else I can implement basically -f tail with a custom separator.


ok - using Kelly we advise, I check and update the scanner, it works. Thanks!

if anyone has suggestions for improving plz do!

 File inputFile = new File("C:/test.txt"); InputStream is = new FileInputStream(inputFile); InputStream bis = new BufferedInputStream(is); //bis.skip(inputFile.length()); Scanner src = new Scanner(bis); src.useDelimiter("\n2010-05-01 "); while (true) { while(src.hasNext()){ System.out.println("[ " + src.next() + " ]"); } Thread.sleep(50); if(bis.available() > 0){ src = new Scanner(bis); src.useDelimiter("\n2010-05-01 "); } } 
+6
java java.util.scanner io tail
source share
1 answer

I would suggest that Scanner parses bis , which is buffered, but the buffer is never updated. You may rely on BufferedInputStream or Scanner to continue reading bytes from the stream, but I think you have to do it yourself.

From Javadocs:

Added BufferedInputStream functionality for another input stream, namely the ability to buffer input and label support and reset. When a BufferedInputStream is created, an internal buffer array is created. In the form of bytes from the stream, the internal buffer is read or skipped as necessary, containing the input stream, many bytes at a time. The label operation remembers the points in the input stream and the reset operation causes all bytes to be read from the moment of the last mark to re-read the bytes taken from the contained input stream.

+1
source share

All Articles