我有一个相当棘手的问题
有没有办法检查文件是否已写入内容?
<小时/>这是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); }
}
关于java - 如何检查某些内容是否已写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458733/