我有一个 java 进程 A
调用 FileOutputStream.flush() 刷新内容,还有另一个进程 B
读取文件内容。在大多数情况下,进程 B
可以很好地读取内容。然而,有时 B
报告得到了不正确的内容。
我的问题是,如果写进程在调用FileOutputStream.close()之前调用FileOutputStream.flush()后立即崩溃,java运行时能否保证读进程仍然可以读取flush之前写入的全部内容?我们是否必须调用 FileOutputStream.getFD().sync()
以确保文件已写入磁盘?
下面是我对这个案例的测试程序:
作者:(请注意,我有意不调用 FileOutputStream.close())
import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
for (int j = 0; j < 100; j++) {
File file = new File("/tmp/test");
if (file.exists()) {
file.delete();
}
FileOutputStream outputStream = null;
outputStream = new FileOutputStream("/tmp/mytest");
String content = "";
for (int i = 0; i < 100 - j; i++) {
content += "," + Integer.toString(i);
}
outputStream.write(content.getBytes());
outputStream.flush();
System.exit(-1);
}
}
}
读者:
import java.io.File;
import java.util.Scanner;
public class MyReader {
public static void main(String[] args) throws Exception {
File file2 = new File("/tmp/mytest");
Scanner sc = new Scanner(file2);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
sc.close();
}
}
最佳答案
FileOutputStream
不使用任何缓冲区,因此 flush 方法为空。叫不叫都没用。
The source code of class
FileOutputStream
hasn't a custom version of method flush. So the flush method used is the version of its super classOutputStream
. The code of flush inOutputStream
is the following
public void flush() throws IOException {
}
有关更多信息,请参阅此答案:
关于java - FileOutputStream.flush() 能否保证其他进程能够一致读取文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130977/