Home » Core Java » io » BufferedOutputStream » Java BufferedOutputStream 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 BufferedOutputStream Example

In this example we will discuss about BufferedOutputStream class and its usage.
The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

BufferedOutputStream extends FilterOutputStream, which is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.

The BufferedOutputStream exists since JDK1.0.

The structure of BufferedOutputStream

Constructor:

  • BufferedOutputStream(OutputStream out)

    Creates a new buffered output stream to write data to the specified underlying output stream.

  • BufferedOutputStream(OutputStream out, int size)

    Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

The BufferedOutputStream in Java

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

package com.javacodegeeks.examples;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class SimpleBufferedOutputStreamExample {

	public static void main(String[] args) {

		try {
			BufferedOutputStream stream = new BufferedOutputStream(
												new FileOutputStream("textfile.txt"));
			stream.write("Hello, World!".getBytes());
			stream.write(System.lineSeparator().getBytes());
			stream.write("I am writting into a file using BufferedOutputStream".getBytes());
			stream.write(System.lineSeparator().getBytes());
			stream.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

The write() method has two implementations in the BufferedOutputStream class:

The one used in the above example is the write(byte[] b), inherited from the FilterOutputStream class.

Since all these methods accept byte arrays as arguments, we are forced to use the getBytes() method.

Always remember to call the close() method when you’re finished with the BufferedOutputStream instance, or its output won’t be the one you would expect.

The output of the above code is:

Hello, World!
I am writting into a file using BufferedOutputStream

A better usage of BufferedOutputStream

To show a more practical usage of the BufferedOutputStream 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.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class Logger {

	private BufferedOutputStream stream;
	
	public Logger(String filename) throws FileNotFoundException {
		this.stream = new BufferedOutputStream(new FileOutputStream(filename));
	}
	
	public Logger(File f) throws FileNotFoundException {
		this.stream = new BufferedOutputStream(new FileOutputStream(f));
	}
	
	public void log(String s) throws IOException {
		String date = new Date().toString();
		String message = String.format("%s : %s", date, s);
		
		this.stream.write(message.getBytes());
		this.stream.write(System.lineSeparator().getBytes());
		this.stream.flush();
	}
	
	public void close() throws IOException {
		this.stream.close();
	}
}

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

package com.javacodegeeks.examples.mylogger;

import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {

	public static void main(String[] args) {
		try {
			Logger logger = new Logger("log.txt");
			logger.log("Log message 1");
			logger.log("Log message 2");
			logger.close();
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		

	}

}

The output written into the file is this:

Wed Aug 27 19:14:17 PDT 2014 : Log message 1
Wed Aug 27 19:14:17 PDT 2014 : Log message 2

More about the BufferedOutputStream in Java

The BufferedOutputStream class does not directly write into the output stream. 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 stream.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 BufferedOutputStream usage in a try-catch block.

Download Code

Download
You can download the full source code of this example here : BufferedOutputStreamExample
(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