Home » Core Java » io » BufferedWriter » Java BufferedWriter Example

About Aldo Ziflaj

Aldo Ziflaj
Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.

Java BufferedWriter Example

In this example we will discuss about the BufferedWriter class and its usage. BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

BufferedWriter extends Writer, which is an abstract class for writing to character streams. The only methods that a subclass must implement are
write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.

The BufferedWriter class exists since JDK1.1.

The structure of BufferedWriter

Constructor:

  • BufferedWriter(Writer out)

    Creates a buffered character-output stream that uses a default-sized output buffer.

  • BufferedWriter(Writer out, int sz)

    Creates a new buffered character-output stream that uses an output buffer of the given size.

The BufferedWriter in Java

To see how the BufferedWriter is used to write in a file, create a class called SimpleBufferedWriterExample with this source code:

package com.javacodegeeks.examples;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class SimpleBufferedWriterExample {

	public static void main(String[] args) {
		
		String greetings = "Hello!";
		String description = "I am written into a file";
		
		try {
			BufferedWriter writer = new BufferedWriter(
					new FileWriter(new File("textfile.txt")));
		
			writer.write(greetings);
			writer.newLine();
			writer.write(description);
			writer.close();
			System.out.println("End");
		
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

}

The BufferedWriter gets a Writer as a parameter, and FileWriter extends OutputStreamWriter, which itself extends Writer abstract class.

I used the write() method to write into the file, and the newLine() method to create a new line, since not all Operating Systems accept the \n as the end-line character.

What’s most important, is the close() method call in the end. Always remember to call this when you are finished with the BufferedWriter.

The output of the file is:

Hello!
I am written into a file

A better usage of BufferedWriter

To show a more practical usage of the BufferedWriter in Java, I created a simple Logger, which can be used to log data into a text file. So, create a class called Logger into the mylogger package, and put this code into it:

package com.javacodegeeks.examples.mylogger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class Logger {
	private BufferedWriter writer;
	
	public Logger(String filename) throws IOException {
		this.writer = new BufferedWriter(new FileWriter(new File(filename)));
	}
	
	public Logger(File logFile) throws IOException {
		this.writer = new BufferedWriter(new FileWriter(logFile));
	}
	
	public void log(String s) throws IOException {
		String date = new Date().toString();
		this.writer.write(date+" : "+s);
		this.writer.newLine();
		this.writer.flush();
	}
	
	public void close() throws IOException {
		this.writer.close();
	}

}

This class creates a Logger object which you can use to log into a file by calling the log() method. You can notice how I used flush() method to write into the file.

To test this, create a new class, called Main, with this source code:

package com.javacodegeeks.examples.mylogger;

import java.io.IOException;

public class Main {

	public static void main(String[] args) {

		try {
			Logger log = new Logger("log1.txt");
			log.log("Test 1");
			log.log("Test 2");
			log.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

The output written into the file is this:

Wed Aug 27 11:45:19 PDT 2014 : Test 1
Wed Aug 27 11:45:19 PDT 2014 : Test 2

More about the BufferedWriter in Java

By creating a BufferedWriter like this:

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

you would be able to write into the output stream.

The BufferedWriter class does not directly write into the output stream (which may or may not be a file). It actually writes into a buffer, which then is written into the stream for better performance. Remember, you can set the size of this buffer in the constructor, or leave it as default. When the close() method is called, the not written buffer gets written into the stream. To witness this, try removing the writer.close() from the above example and rerun the program. You will see that nothing will be written into the file.

If you don’t want to close the stream but need to flush the buffer into the file, you may use the flush() method. Any usage of methods like flush() or write() after the close() method is called will result into an IOException thrown.

Finally, all the methods can throw an IOException, so make sure to wrap the BufferedWriter usage in a try-catch block.

Download Code

Download
You can download the full source code of this example here : BufferedWriterExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of