java - FileOutputStream.flush() 能否保证其他进程能够一致读取文件内容?

标签 java linux io

我有一个 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 class OutputStream. The code of flush in OutputStream is the following

public void flush() throws IOException {
}

有关更多信息,请参阅此答案:

flush and close

关于java - FileOutputStream.flush() 能否保证其他进程能够一致读取文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130977/

相关文章:

java - 如何停止子类的序列化?

javascript - 如何在对象模式下一次性在 Node.js 流中分配 block ?

windows - 您会推荐哪些资源来学习操作系统安全性?

c - Linux 管道 : Bad file descriptor in functions read and write

python - concurrent.futures 和 POSIX Linux 中异步 I/O 的区别

java - 如何安全地将 List 转换为 csv 字节数组?

java - 异常已被其他异常错误捕获

java - 如何在运行时根据构造函数参数在父类(super class)中创建子类对象(在Java中)

java - 线程 hibernate 和精确计时

linux - 剪贴板 api 是否已从 gtk4 中删除?