【问题标题】:can FileOutputStream.flush() guarantee that other processes can read the file content consistently?FileOutputStream.flush() 可以保证其他进程可以一致地读取文件内容吗?
【发布时间】:2018-07-02 07:22:49
【问题描述】:

我有一个 java 进程 A 调用 FileOutputStream.flush() 来刷新内容,并有另一个进程 B 来读取文件内容。在大多数情况下,进程B 可以正常读取内容。但是,有时B 会报告获取不正确的内容。

我的问题是,如果在调用 FileOutputStream.close() 之前调用 FileOutputStream.flush() 之后写入进程立即崩溃,java 运行时是否可以保证读取器仍然可以读取在刷新之前写入的全部内容?我们必须调用FileOutputStream.getFD().sync() 来确保文件已写入磁盘吗?

以下是我在这个案例上的测试程序:

Writer:(注意我故意不调用 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();
    }

}

【问题讨论】:

  • 确切的错误信息是什么?
  • 你是同时读写文件吗?
  • @DforTye 我们没有同时读取文件。读取器仅在写入退出后读取文件。
  • 请注意,您并没有关闭您的outputStream

标签: java linux io


【解决方案1】:

FileOutputStream不使用任何缓冲区,因此刷新方法为空。叫不叫也没用。

FileOutputStream 类的源代码没有自定义版本 方法冲洗。所以使用的flush方法是它的super的版本 类OutputStreamOutputStream 中的刷新代码是 关注

public void flush() throws IOException {
}

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

flush and close

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 2023-04-10
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2021-09-15
    相关资源
    最近更新 更多