在文件写入时读取文件 [英] reading a file while it's being written

查看:166
本文介绍了在文件写入时读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了有关此主题的stackoverflow上的一些帖子,但我仍然感到困惑。当读取当前用Java编写的文件时,如何跟踪实际写入的行数,以便不会得到奇怪的读取结果?

I've read some posts on stackoverflow about this topic but I'm still confused. When reading a file that is currently being written in Java, how do you keep track of how many lines have actually been written so that you don't get weird read results?

编辑:对不起,我应该提到写它的文件是用C ++编写的,读取它的文件是用Java编写的,因此变量不能真正轻易共享

sorry, I should have mentioned that the file writing it is in C++ and the one reading it is in Java so variables can't really be shared easily

推荐答案


当读取当前用Java编写的文件时,如何跟踪实际写入的行数,这样就不会出现奇怪的读取结果?

When reading a file that is currently being written in Java, how do you keep track of how many lines have actually been written so that you don't get weird read results?

问题是你永远无法确定文件的当前最后一个字符是否为行尾。如果它是行终止符,你就可以了。如果 BufferedReader.readLine()将其解释为没有行终止符的完整行...并且会产生奇怪的结果。

The problem is that you can never be sure that the current last character of the file is the end of a line. If it is a line terminator, you are OK. If BufferedReader.readLine() will interpret it as a complete line without a line terminator ... and weird results will ensue.

您需要做的是实现自己的行缓冲。当你得到一个EOF时,你要等到文件增长一些,然后继续读取该行。

What you need to do is to implement your own line buffering. When you get an EOF you wait until the file grows some more and then resume reading the line.

或者,如果你使用的是Java 7或更高版本,那么文件观察器API 允许您监视文件写入没有轮询文件的大小。

Alternatively, if you are using Java 7 or later, the file watcher APIs allow you to watch for file writes without polling the file's size.

顺便说一下,有一个Apache commons类专为做这种事情:

By the way, there is an Apache commons class that is designed for doing this kind of thing:

http://commons.apache.org/io/api-2.0/org/apache/commons/io/input/Tailer.html

这篇关于在文件写入时读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆