Java 扫描仪不会跟踪文件
尝试跟踪/解析一些日志文件。条目以日期开头,然后可以跨越多行。
这可行,但不会看到要归档的新条目。
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() + " ]");
}
}
扫描仪的 next() 或 hasNext() 似乎没有检测到文件的新条目。
知道我还能如何实现,基本上,带有自定义分隔符的 tail -f 。
好的 - 根据凯利的建议,我正在检查&刷新扫描仪,这有效。谢谢 !!
如果有人有改进建议,请提出!
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 ");
}
}
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.
Any idea how else I can implement, basically, a tail -f with custom delimiter.
ok - using Kelly's advise i'm checking & refreshing the scanner, this works. Thank you !!
if anyone has improvement suggestions 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 ");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜测扫描仪正在解析已缓冲的bis,但缓冲区永远不会刷新。您可能依赖 BufferedInputStream 或 Scanner 来继续从流中读取字节,但我认为您必须自己这样做。
来自 Java 文档:
I would guess that the Scanner is parsing
bis
which is buffered but the buffer is never getting refreshed. 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.From the Javadocs: