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

发布于 2024-12-12 07:02:44 字数 240 浏览 0 评论 0原文

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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸印温柔 2024-12-19 07:02:44

如果程序的一部分正在写入文件,那么您应该能够在另一个线程中使用普通的 new FileInputStream(someFile) 流读取该文件,尽管这取决于操作系统对此类文件的支持行动。您不需要同步任何内容。现在,您受到输出流以及程序的写入部分调用flush() 的频率的影响,因此可能会出现延迟。

这是我编写的一个小测试程序,证明它工作正常。阅读部分只是循环,看起来像:

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

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);
}
云醉月微眠 2024-12-19 07:02:44

假设文件写入行为是库固有的,您应该检查其文档以查看是否可以避免写入文件系统。
一般来说,如果您想读取正在写入的文件(即 *nix tail-like 行为),您可以使用 java.io.RandomAccessFile

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文