Reading data from a File while it is being written to

后端 未结 2 1101
时光说笑
时光说笑 2021-02-06 13:37

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 bina

相关标签:
2条回答
  • 2021-02-06 14:04

    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);
    }
    
    0 讨论(0)
  • 2021-02-06 14:05

    assuming file writing behaviour is intrinsic to the library, you should check its documentation to see if you can avoid writing to the file system. Generally speaking, if you want to read a file that is being written to (i.e. *nix tail-like behaviour), you can use java.io.RandomAccessFile

    0 讨论(0)
提交回复
热议问题