Writing files shares many considerations with reading files.
As such, the pattern is rather similar, but instead of a FileReader, we use a FileWriter, and instead of a BufferedReader, we use a BufferedWriter.
try(FileWriter fw = new FileWriter(theFile);
BufferedWriter writer = new BufferedWriter(fw)) {
// use the writer
} catch(IOException e) {
// handle IOException
}
The BufferedWriter does not have a writeLine or printLine method.
Instead, you have to use the write method and add a newline character yourself:
writer.write(someString + "\n");
Here, "\n" is a string consisting of a single newline character '\n'. Backslashes \ start what is called an escape sequence, expressing characters that are not easily printable.
To include a backslash itself, you have to write "\\".
The newline character '\n' (also called "line feed" or "LF") is the standard way of expressing line breaks on Linux and modern MacOS.
(Very) old Macs used a different character, '\r' (called "carriage return" or "CR", representing the idea of resetting the position of your typewriter to the start of a line).
Not to be outdone, Windows programs represent line breaks using a combination of the two, as "\r\n" (also described as "CRLF").
However, most Windows programs also recognize '\n' on its own as a line break (and BufferedReader considers any of the three to be terminating a line).
For this reason, it is usually fine to stick with just using '\n' as line break if you do not need to keep compatibility with specific Windows programs.
Alternatively, you can use BufferedReader's newLine method, which will write a system-specific line break (i.e. usually either '\n' or "\r\n") to your file at the current position:
writer.write(someString);
writer.newLine();
Finally, BufferedReader does not necessarily write everything to your file right away.
If you want to make sure that everything you have written so far makes it to your file even if your program crashes at some later point, use the method flush().
writer.write(someString);
writer.newLine();
writer.flush(); // everything written so far will
// definitely be written to the file now
In any case, flush will automatically be part of closing the file, say at the end of a try-with-resources.