How do I use Java to read from a file that is actively being written to?

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.

Leave a Comment