我有一个 Writer 程序,它将一行文本写入文件,然后等到用户点击返回,然后再写入另一行,然后退出。只有在那之后才关闭文件。编码:
public class Writer {
Writer() {
}
public static String[] strings =
{
"Hello World",
"Goodbye World"
};
public static void main(String[] args)
throws java.io.IOException {
java.io.FileOutputStream pw =
new java.io.FileOutputStream("myfile.txt");
for(String s : strings) {
pw.write(s.getBytes());
System.in.read();
}
pw.close();
}
}
首先开始:
写手
然后我还有一个阅读器程序,只要文件的写入尚未完成(即 pw.close() 尚未被调用),它就应该(我预期)阻塞。编码:
public class ReaderFIS extends Object {
ReaderFIS() {
}
public static void main(String[] args) throws Exception {
java.io.FileInputStream in = new java.io.FileInputStream("myfile.txt");
int ch = -1;
while((ch = in.read()) >= 0) {
System.out.println("ch = " + ch);
}
System.out.println("Last ch = " + ch);
System.out.println("exiting");
}
}
从...开始:
java阅读器FIS
现在我希望 read() 在阅读第一个“Hello World”文本后阻塞,基于 Javadoc 文档中的这个:
从此输入流中读取一个字节的数据。如果还没有输入可用,则此方法会阻塞。通过:http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read()
但是 ReaderFIS 在阅读“Hello World”后立即完成,并且显然看到了 EOF!所以它不会阻塞!它转储字符值,然后是 -1,然后打印“exiting”。
输出: ch = 72 ch = 101 ch = 108 ch = 108 ch = 111 ch = 32 ch = 87 ch = 111 ch = 114 ch = 108 ch = 100 最后一个 ch = -1 退出
我尝试的其他变体是:通过 getChannel() 读取,通过 getChannel() 检查是否可以锁定(),使用 available(),尝试使用缓冲区读取 read(),尝试 readLine(),连续写入一个字符文件在每次写入之间有 500 毫秒的暂停,不写任何东西,只是在 Writer 中保持文件打开。
这些变化都不会导致 ReaderFIS 程序阻塞,它总是会结束。
为什么阅读器程序不阻塞?我错过了一些非常明显的东西吗?ReaderFIS 程序似乎找到了 EOF (-1),但为什么呢?该文件尚未被 Writer 程序关闭。
“有趣”的旁注: System.in.read() 被阻塞了!(并等待用户按 Enter)。
PS:在 Windows XP 和 Suse Linux 上试过这个。在 Windows 上,当编写器运行时,我无法删除文件(正如我所料)。
问候, 马可