Skip to main content

Java BufferedWriter Class

Java BufferedWriter Class is a crucial class found in Java's java.io package. It creates a character-output stream, buffering characters to provide efficient writing of single characters, arrays, and strings.

What is BufferedWriter Class?

The BufferedWriter class is a character stream class that is used for handling character files. This class operates by making requests to the operating system for large chunks of characters and storing them in a buffer. This buffer is then used for the individual read and write operations, which is more efficient than making a separate operating system request for each character.

BufferedWriter Class Declaration

The declaration for java.io.BufferedWriter class is:

public class BufferedWriter
extends Writer

Constructors in Java BufferedWriter Class

  • BufferedWriter(Writer out): Creates a new buffered character-output stream using a default-sized output buffer.

  • BufferedWriter(Writer out, int sz): Creates a new buffered character-output stream using an output buffer of the given size.

Methods of BufferedWriter Class

  • void newLine(): Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

  • void write(int c): Writes a single character.

  • void write(char[] cbuf, int off, int len): Writes a portion of an array of characters.

  • void write(String s, int off, int len): Writes a portion of a string.

  • void flush(): Flushes the stream. This will write any buffered output to the underlying stream.

  • void close(): Closes the stream, flushing it first.

Example of BufferedWriter Class

Here is an example of how to use the BufferedWriter class:

import java.io.*;

public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("test.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to Java BufferedWriter Class tutorial.");
buffer.close();
System.out.println("Success");
}
}

In this example, we're writing a string to the file 'test.txt' using BufferedWriter. If the operation is successful, it will print "Success" on the console.

Conclusion

The BufferedWriter class in Java makes it easy and efficient to write to character output streams like files. By buffering characters, it allows for the efficient writing of single characters, arrays, and strings. In this tutorial, we've covered the basic usage of the BufferedWriter class, including its constructors and methods. We've also provided an example of how to use this class to write to a file.

Remember, it's always important to close the BufferedWriter once you're done with it to free up system resources and ensure that all changes are saved to the file. This can be done using the close() method or by using the try-with-resources statement.