+ Reply to Thread
Results 1 to 2 of 2

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

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    14

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

    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?

  2. #2
    Junior Member
    Join Date
    Jun 2012
    Posts
    14
    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.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts