简体   繁体   English

Java Scanner不会关注文件

[英]Java Scanner won't follow file

Trying to tail / parse some log files. 试图拖尾/解析一些日志文件。 Entries start with a date then can span many lines. 条目以日期开头,然后可以跨越多行。

This works, but does not ever see new entries to 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() + " ]");
    }
}

Doesn't seem like Scanner's next() or hasNext() detects new entries to file. 看起来不像Scanner的next()或hasNext()检测到新的文件条目。

Any idea how else I can implement, basically, a tail -f with custom delimiter. 任何想法我还能实现,基本上,一个带有自定义分隔符的tail -f。


ok - using Kelly's advise i'm checking & refreshing the scanner, this works. 好的 - 使用凯利的建议我正在检查和刷新扫描仪,这是有效的。 Thank you !! 谢谢 !!

if anyone has improvement suggestions plz do! 如果有人有改进建议PLZ吗!

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 ");
    }
}

I would guess that the Scanner is parsing bis which is buffered but the buffer is never getting refreshed. 我猜测Scanner正在解析被缓冲的bis ,但缓冲区永远不会刷新。 You might be relying on the BufferedInputStream or the Scanner to keep reading bytes from the stream but I think you have to do that yourself. 您可能依赖BufferedInputStream或Scanner来继续从流中读取字节,但我认为您必须自己这样做。

From the Javadocs: 来自Javadocs:

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. BufferedInputStream将功能添加到另一个输入流 - 即缓冲输入并支持标记和重置方法的功能。 When the BufferedInputStream is created, an internal buffer array is created. 创建BufferedInputStream时,会创建一个内部缓冲区数组。 As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. 当读取或跳过来自流的字节时,内部缓冲区根据需要从包含的输入流中重新填充,一次多个字节。 The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream. 标记操作记住输入流中的一个点,并且重置操作使得从最近的标记操作开始读取的所有字节在从包含的输入流中获取新字节之前被重新读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM