在写入文件时从文件中读取数据 [英] Reading data from a File while it is being written to

查看:169
本文介绍了在写入文件时从文件中读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个专有的Java库,将其数据直接保存到 java.io.File 中,但我需要能够读取数据,以便直接进行流式处理。数据是二进制的,一些媒体文件。

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.

java.io.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!?

我希望跳过写入文件系统部分,因为我从applet使用它,在这种情况下需要额外的权限。

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.

推荐答案

如果我的一部分你的程序正在写入一个文件,然后你应该能够在另一个线程中使用普通的新的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);
}

这篇关于在写入文件时从文件中读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆