答案似乎是“不”…“是的”。似乎没有真正的方法来知道一个文件是否被另一个应用程序打开进行写入。所以,从这样一个文件中读取将一直进行到内容耗尽为止。我接受了迈克的建议,写了一些测试代码:
java将一个字符串写入文件,然后等待用户单击Enter,然后再将另一行写入文件。这个想法是,它可以启动,然后读者可以开始看它如何处理“部分”文件。我写的阅读器在reader.java中。
Java语言
public class Writer extends Object
{
Writer () {
}
public static String[] strings =
{
"Hello World",
"Goodbye World"
};
public static void main(String[] args)
throws java.io.IOException {
java.io.PrintWriter pw =
new java.io.PrintWriter(new java.io.FileOutputStream("out.txt"), true);
for(String s : strings) {
pw.println(s);
System.in.read();
}
pw.close();
}
}
Java语言
public class Reader extends Object
{
Reader () {
}
public static void main(String[] args)
throws Exception {
java.io.FileInputStream in = new java.io.FileInputStream("out.txt");
java.nio.channels.FileChannel fc = in.getChannel();
java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);
while(fc.read(bb) >= 0) {
bb.flip();
while(bb.hasRemaining()) {
System.out.println((char)bb.get());
}
bb.clear();
}
System.exit(0);
}
}
不能保证本规范是最佳实践。
这将保留Mike建议的选项,即定期检查是否有新数据要从文件中读取。当确定读取已完成时,需要用户干预关闭文件读取器。或者,需要让读卡器知道文件的内容,并且能够确定和结束写入条件。如果内容是XML,则可以使用文档结尾来表示这一点。