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

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

问题描述

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



我假设有可能做到这一点,但使用Java时涉及到的陷阱是什么?如果读取到达写入,是否等待更多的写入,直到文件关闭,或读取会在此时抛出异常?如果是后者,那么我该怎么办?

我的直觉正在把我推向BufferedStreams。这是要走的路吗?

解决方案

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

  boolean running = true; 
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(out.txt)); $()
$ b public void run(){
while(running){
if(reader.available()> 0){
System.out.print( char)reader.read());
}
else {
try {
sleep(500);
}
catch(InterruptedException ex){
running = false;




code $


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



哦,我会告诉这个:我使用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 real time.

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?

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