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

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

问题描述

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



我假设是可能这样做,但是在使用Java时涉及的是什么?如果阅读能够追溯到写作,那么它只会等待更多的写入,直到文件关闭,或者在这一点上读取异常呢?如果是后者,那我该怎么办?



我的直觉正在推向BufferedStreams。是这样吗?

解决方案

无法使用 FileChannel.read ByteBuffer)因为它不是阻塞读取。没有得到下面的代码工作:

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

当然,同样的事情会像计时器一样工作,而不是线程,但是我将其留给程序员。我仍然在寻找一个更好的方法,但这对我来说现在很有用。



哦,我会告诉你:我使用的是1.4.2 。是的,我知道我还在石头时代。


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 realtime.

I assume it is possible to do this, but what are the gotchas 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?

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

解决方案

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.

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天全站免登陆