It's easy to use the Files class.
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
But if you write the same file several times, it's slow because you open it, close it, and do it a lot.
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
out.println("the text");
//more code
out.println("more text");
//more code
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Do it like this.
The second factor in FileWriter
is whether to add it to the file.
If you are going to use it several times, I recommend BufferedWriter
.
PrintWriter
gives println
access, which is the same as System.out.
try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))); out.println("the text"); out.close(); } } catch (IOException e) { //exception handling left as an exercise for the reader }
© 2024 OneMinuteCode. All rights reserved.