我有一个相当棘手的问题
有没有办法检查是否有东西写入文件?
这是由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();
}
}
}
}
答案 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); }
}