BufferedWriter
Syntax#
- new BufferedWriter(Writer); //The default constructor
- BufferedWriter.write(int c); //Writes a single character
- BufferedWriter.write(String str); //Writes a string
- BufferedWriter.newLine(); //Writes a line separator
- BufferedWriter.close(); //Closes the BufferedWriter
Remarks#
- If you try to write from a
BufferedWriter
(usingBufferedWriter.write()
) after closing theBufferedWriter
(usingBufferedWriter.close()
), it will throw anIOException
. - The
BufferedWriter(Writer)
constructor does NOT throw anIOException
. However, theFileWriter(File)
constructor throws aFileNotFoundException
, which extendsIOException
. So catchingIOException
will also catchFileNotFoundException
, there is never a need for a second catch statement unless you plan on doing something different with theFileNotFoundException
.
Write a line of text to File
This code writes the string to a file. It is important to close the writer, so this is done in a finally
block.
public void writeLineToFile(String str) throws IOException {
File file = new File("file.txt");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(str);
} finally {
if (bw != null) {
bw.close();
}
}
}
Also note that write(String s)
does not place newline character after string has been written. To put it use newLine()
method.
Java 7 adds the java.nio.file
package, and try-with-resources:
public void writeLineToFile(String str) throws IOException {
Path path = Paths.get("file.txt");
try (BufferedWriter bw = Files.newBufferedWriter(path)) {
bw.write(str);
}
}