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

时间:2018-03-23 21:50:28

标签: java bufferedreader

我有一个相当棘手的问题

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

这是由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();
          }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

写完文件后读取文件

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); }
}