Reputation: 35
I have a rather tricky question
Is there a way to check if something has been written into a file?
This is a piece of code written by Eric Petroelje, and I need to check if the "Hello world" has been written into a file.
This would be useful for checking if a big number is written to a text file. Thank you in advance!
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();
}
}
}
}
Upvotes: 1
Views: 1952
Reputation: 2392
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); }
}
Upvotes: 1