Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from a File while it is being written to

Tags:

java

file

stream

I'm using a propriatery Java library that saves its data directly into a java.io.File, but I need be able to read the data so it's directly streamed. Data is binary, some media file.

The java.io.File is passed as an argument to this library, but I don't know of a way to get a stream out of it. Is there some simple way to do this, except opening the file also for reading and trying to sync read/write operations!?

Prefferably I would like to skip the writing to the file system part since I'm using this from an applet and in this case need extra permissions.

like image 962
user1015922 Avatar asked Oct 27 '11 06:10

user1015922


1 Answers

If one part of your program is writing to a file, then you should be able to read from that file using a normal new FileInputStream(someFile) stream in another thread although this depends on OS support for such an action. You don't need to synchronize anything. Now, you are at the mercy of the output stream and how often the writing portion of your program calls flush() so there may be a delay.

Here's a little test program that I wrote demonstrating that it works fine. The reading section just is in a loop looks something like:

FileInputStream input = new FileInputStream(file);
while (!Thread.currentThread().isInterrupted()) {
    byte[] bytes = new byte[1024];
    int readN = input.read(bytes);
    if (readN > 0) {
        byte[] sub = ArrayUtils.subarray(bytes, 0, readN);
        System.out.print("Read: " + Arrays.toString(sub) + "\n");
    }
    Thread.sleep(100);
}
like image 72
Gray Avatar answered Oct 18 '22 08:10

Gray