Learn the basics of BufferedWriter, creating its instance, internal buffer size and writing the content into a file in Java using BufferedWriter
. You can use the example as a template and reuse or rewrite them based on the application requirements.
1. BufferedWriter class
The BufferedWriter class applies the data buffering before writing text to a character-output stream. The buffering helps in the efficient writing of single characters, arrays, and strings.
During write operations, the characters are first written to the internal buffer of the buffered writer. Once the internal buffer is filled or the writer is closed, the whole characters in the buffer are written to the disk. This minimizes the number of write operations, thus improving performance.
A BufferedWriter :
- is a subclass of java.io.Writer class.
- maintains an internal buffer of 8192 characters.
- is used to make lower-level classes like
FileWriter
more efficient and easier to use. - uses relatively large chunks of data at once, thus minimizing the number of write operations for better performance.
1.1. Creating BufferedWriter
As said earlier, wrap the FileWriter
instance into a BufferedWriter
object.
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
1.2. Configure Buffer Size
To configure the default buffer size, pass the new size in its constructor.
The default buffer size is best in most cases. If you customize it then be careful about the new size. An extra-large or extra-small buffer may actually decrease the performance. So you need to test it out for different sizes, and then choose what works best for you.
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"), 65536); //64 KB
2. Writing with BufferedWriter
The FileWriter
class is meant for writing streams of characters. Use one of the write() methods:
write()
– writes a single character to the internal buffer of the writerwrite(char[] array)
– writes the characters from the specified array to the internal buffer of the writerwrite(String data)
– writes the specified string to the internal buffer of the writer
In the given example, we are writing a string to a file using the BufferedWriter.
String string = "Hello Learner !! Welcome to howtodoinjava.com."; File outFile = new File("c:/temp/samplefile.txt"); if (!file.exists()) { file.createNewFile(); } try(FileWriter fw = new FileWriter(outFile); BufferedWriter bw = new BufferedWriter(fw);) { bw.write(string); } catch (IOException e) { e.printStackTrace(); }
3. Conclusion
In this Java tutorial, we learned to create BufferedWriter with default and custom internal buffer sizes. We also learned to write data into a file using it.
Happy Learning !!
Comments