gpt4 book ai didi

java - Java FileInputStream 是否为写入锁定文件

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:11 26 4
gpt4 key购买 nike

我正在两个独立的程序之间创建一个快速的桥梁。

一个程序写入一个文件,而我的程序同时从中读取。

似乎一旦我调用第一次读取,写入就完全被阻止了。

为什么会发生这种情况,解决方法是什么?

 // Create Named Pipe
Runtime.getRuntime.exec("mkfifo /tmp/mypipe")

val stream = new FileInputStream("/tmp/mypipe")

val in = new BufferedReader(new InputStreamReader(stream))

// File opened for reading. No blocking at this point.

while (true) {

println(in.readLine())

// File read. Now blocking.

}

更新:

这个文件实际上是一个用mkfifo/tmp/mypipe创建的命名管道。我尝试将它与常规 File 一起使用,它工作得很好 - 显示所有数据。

我正在使用命名管道,因为我不希望磁盘 IO 开销。

最佳答案

如果非要我打赌,我会说这是一个缓冲问题。

最初我在想BufferedReader可能会尝试填满它的整个缓冲区,但看起来只要它读取了一些东西它就会很高兴。请参阅 fill() 方法。

如果您使用 readLine(),还有一个问题是您获得的输入是否包含换行符。

根据源程序产生的输出量,可能发生的另一件事是与管道缓冲有关。会 this answer帮助?您也可以尝试结束源程序(例如 ^C 等),然后查看目标程序是否打印任何内容。

This页面表明缓冲可能是一个问题:

However, if a buffered write is used, the buffer is not made available to the reader until the buffer is flushed. This flushing occur.s when more data is written to the buffer than the maximum buffer size (BUFSIZ set in stdio.h), or when the pipe is closed by the writer.

关于java - Java FileInputStream 是否为写入锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com