Java BufferedOutputStream class is used for buffering an output stream. It internally uses a buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:
OutputStream os= new BufferedOutputStream(new FileOutputStream("sample.txt"));
BufferedOutputStream class Constructors
- 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.
BufferedOutputStream class Methods
- void flush() - Flushes this buffered output stream.
- void write(byte[] b, int off, int len) - Writes len bytes from the specified byte array starting at offset off to this buffered output stream.
- void write(int b) - Writes the specified byte to this buffered output stream.
BufferedOutputStream class Example
This program uses text content as input and writes to file named "sample.txt".
String content = "This is the text content";
Note: This program uses try-with-resources. It requires JDK 7 or later.
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* The class demonstrate the usage of BufferedOutputStream class methods.
* @author javaguides.net
*
*/
public class BufferedOutputStreamExample {
public static void main(String[] args) {
File file = new File("sample.txt");
String content = "This is the text content";
try (OutputStream out = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(out);) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
bout.write(content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reference
BufferedOutputStream Javadoc 8
Related Java I/O Classes
- FileOutputStream Class in Java
- FileInputStream Class in Java
- ByteArrayOutputStream Class in Java
- ByteArrayInputStream Class in Java
- BufferedWriter Class in Java
- BufferedReader Class in Java
- BufferedOutputStream Class in Java
- BufferedInputStream Class in Java
- FileWriter Class in Java
- FileReader Class in Java
- DataOutStream Class in Java
- DataInputStream Class in Java
- ObjectOutputStream Class in Java
- ObjectInputStream Class in Java
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment