且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在写入文件时从文件中读取数据

更新时间:2023-02-07 11:25:04

如果我的一部分你的程序正在写入一个文件,然后你应该能够在另一个线程中使用普通的新的FileInputStream(someFile)流来读取该文件,尽管这取决于操作系统对OS的支持这样的行动。您不需要同步任何东西。现在,您受输出流的支配以及程序的写入部分调用 flush()的频率,因此可能会有延迟。

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);
}