Java BufferedWriter

‮figi.www‬tidea.com

Java BufferedWriter is a class that writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. It is a higher-level class that provides more functionality than the lower-level FileWriter and OutputStreamWriter classes.

Here's an example of how to use BufferedWriter to write to a file:

try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
    writer.write("Hello, world!");
    writer.newLine();
    writer.write("This is a test.");
} catch (IOException e) {
    e.printStackTrace();
}

In this example, we create a new BufferedWriter object and pass it a FileWriter object that writes to the file "example.txt". We then use the write() method to write two lines of text to the file, and the newLine() method to insert a newline between the lines. Note that we use a try-with-resources statement to automatically close the BufferedWriter when we're done with it, and we catch any IOException that might occur during the write operation.

The BufferedWriter class provides several methods that can be used to write to the output stream:

  1. write(int c): This method writes a single character to the output stream.

  2. write(String str): This method writes a string of characters to the output stream.

  3. write(char[] cbuf): This method writes an array of characters to the output stream.

  4. write(char[] cbuf, int off, int len): This method writes a portion of an array of characters to the output stream, starting at the specified off offset and writing len characters.

  5. newLine(): This method writes a platform-specific newline character(s) to the output stream.

  6. flush(): This method flushes the output stream, writing any buffered data to the underlying stream.

  7. close(): This method closes the output stream and releases any system resources associated with it.

Note that many of these methods can throw an IOException if there is an error while writing to the stream. Therefore, it is important to handle exceptions appropriately when using these methods.