如何检查是否已将某些内容写入文件?

how to check if something has been written into file?

我有一个比较棘手的问题

有没有办法检查是否有东西被写入文件?


这是Eric Petroelje写的一段代码,我需要检查"Hello world"是否已经写入文件

这对于检查是否将大数字写入文本文件很有用。 提前致谢!

public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}

写入后读取文件

public boolean writeToTXT(String text, String path)
{
    BufferedWriter output = null;
    try {
        File file = new File(path);
        output = new BufferedWriter(new FileWriter(file));
        output.write(text);
        output.flush();
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
        
    try(BufferedReader br = new BufferedReader(new FileReader(path))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    return sb.toString().equals(text); }
}