简体   繁体   English

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

[英]Reading data from a File while it is being written to

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. 我正在使用一个专有的Java库,将其数据直接保存到java.io.File ,但我需要能够读取数据,以便直接进行流式处理。 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. java.io.File作为参数传递给这个库,但我不知道如何从中获取流。 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. 我希望跳过写入文件系统部分,因为我从applet使用它,在这种情况下需要额外的权限。

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. 如果程序的一部分正在写入文件,那么您应该能够使用另一个线程中的普通new FileInputStream(someFile)流从该文件中读取,尽管这取决于操作系统对此类操作的支持。 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. 现在,您受输出流的支配以及程序的写入部分调用flush()频率,因此可能会有延迟。

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

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 (ie *nix tail-like behaviour), you can use java.io.RandomAccessFile 一般来说,如果要读取正在写入的文件(即* nix尾部行为),可以使用java.io.RandomAccessFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM