如何使用 Java 从正在写入的文件中读取数据? [英] How do I use Java to read from a file that is actively being written to?

查看:38
本文介绍了如何使用 Java 从正在写入的文件中读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将信息写入文件的应用程序.此信息在执行后用于确定应用程序的通过/失败/正确性.我希望能够在写入文件时读取文件,以便我可以实时执行这些通过/失败/正确性检查.

I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.

我认为这样做是可能的,但是在使用 Java 时有什么问题?如果读取赶上写入,它会等待更多写入直到文件关闭,还是此时读取会抛出异常?如果是后者,那我该怎么办?

I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then?

我的直觉目前正在将我推向 BufferedStreams.这是要走的路吗?

My intuition is currently pushing me towards BufferedStreams. Is this the way to go?

推荐答案

无法使用 FileChannel.read(ByteBuffer) 使示例工作,因为它不是阻塞读取.但是让下面的代码工作:

Could not get the example to work using FileChannel.read(ByteBuffer) because it isn't a blocking read. Did however get the code below to work:

boolean running = true;
BufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) );

public void run() {
    while( running ) {
        if( reader.available() > 0 ) {
            System.out.print( (char)reader.read() );
        }
        else {
            try {
                sleep( 500 );
            }
            catch( InterruptedException ex ) {
                running = false;
            }
        }
    }
}

当然,同样的事情可以作为计时器而不是线程工作,但我把它留给程序员.我仍在寻找更好的方法,但目前这对我有用.

Of course the same thing would work as a timer instead of a thread, but I leave that up to the programmer. I'm still looking for a better way, but this works for me for now.

哦,我要说明一下:我使用的是 1.4.2.是的,我知道我仍处于石器时代.

Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.

这篇关于如何使用 Java 从正在写入的文件中读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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