In this document, we will explore Java's OutputStream, understand its uses, and look at some of its subclasses with practical examples.
The OutputStream class in the java.io package is an abstract superclass that represents an output stream of bytes. Since OutputStream is an abstract class, it cannot be used directly. Instead, its subclasses are used to write data. It is a fundamental class used for writing binary data to a destination, such as a file, a network socket, or an array of bytes. It serves as the superclass for all classes representing an output stream of bytes.
Uses of OutputStream:
OutputStream is used for:
Sending data over the network. Writing data to other I/O sources like pipes. Subclasses of OutputStream:
To use the functionality of OutputStream, you can use its subclasses, such as:
How to create an OutputStream?
To create an OutputStream, first import the java.io.OutputStream package. Then, create an object using one of its subclasses.
// Creates an OutputStream
OutputStream object = new FileOutputStream();
Here, we have created an output stream object using FileOutputStream. It is because OutputStream is an abstract class, so we cannot create an object of OutputStream.
Note: We can also create the output stream from other subclasses of the OutputStream class.
What is FileOuptutStream?
FileOutputStream is a subclass of OutputStream available since Java 1.0. It is used to write data to a file in binary format, one byte at a time. You can write numbers, characters, text, or image data to the file.
Example: OutputStream Using FileOutputStream
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
try {
OutputStream out = new FileOutputStream("output.txt");
// Converts the string into bytes
byte[] dataBytes = data.getBytes();
// Writes data to the output stream
out.write(dataBytes);
// Closes the output stream
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
In this example:
We create an OutputStream
OutputStream out = new FileOutputStream("output.txt");
The string data is converted into bytes using getBytes() method. To write data to the output.txt file and close the output stream, we implemented some methods.
out.write(); // To write data to the file
out.close(); // To close the output stream
Output:
This is a line of text inside the file.
Alternative: Using the throws Keyword
Instead of using a try-catch block, you can also use the throws keyword with the FileNotFoundException. This simplifies the code by delegating the exception handling responsibility to the calling method or the Java runtime.
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String data = "This is a line of text inside the file.";
OutputStream out = new FileOutputStream("output.txt");
// Converts the string into bytes
byte[] dataBytes = data.getBytes();
// Writes data to the output stream
out.write(dataBytes);
// Closes the output stream
out.close();
}
}
This approach ensures that if any IOException occur, they will be handled by the method that calls main, or by the Java runtime.
BufferedOutputStream:
BufferedOutputStream is another subclass of OutputStream that adds buffering to the underlying output stream. By buffering the output, it reduces the number of I/O operations, making it more efficient, especially for writing large amounts of data.
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("output.txt"));
// Converts the string into bytes
byte[] dataBytes = data.getBytes();
// Writes data to the output stream
out.write(dataBytes);
// Closes the output stream
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Explanation:
We create a BufferedOutputStream object that wraps a FileOutputStream. The string data is converted into bytes using the getBytes() method. The write() method is used to write data to the output.txt file. The close() method closes the output stream. ByteArrayOutputStream
ByteArrayOutputStream is an implementation of OutputStream that can write data into a byte array. The buffer keeps growing as ByteArrayOutputStream writes data to it.
We can keep the default initial size of the buffer as 32 bytes or set a specific size using one of the constructors available.
The important thing to note here is that the method close() has practically no effect. The other methods in ByteArrayOutputStream can be safely called even after close() has been called.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) {
String data = "Hello, ByteArrayOutputStream!";
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byteArrayOutputStream.write(data.getBytes());
byte[] byteArray = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
We create a ByteArrayOutputStream object. The write method writes the byte representation of the string data to the byte array. The toByteArray method returns the data as a byte array. We print the data from the byte array. ObjectOutputStream
ObjectOutputStream can write primitive data types and graphs of Java objects to a destination. We can construct an ObjectOutputStream using an existing OutputStream to write to a specific destination like File.
Please note that it is necessary for objects to implement Serializable for ObjectOutputStream to write them to a destination. You'll learn about it in Java Serialization & Deserialization chapter.
What is PrintStream?
PrintStream is another subclass of OutputStream and provides convenient methods to write data in a human-readable format. It is commonly used for printing textual data to various output destinations, such as the console or a file. Unlike other output streams, a PrintStream never throws an IOException; instead, you can check for errors by calling checkError() method.
How to Create a PrintStream?
You can create a PrintStream to write data to a file, just like with FileOutputStream.
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String data = "This is a line of text inside the file.";
// Creates a PrintStream
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
// Writes data to the output stream
out.println(data);
System.out.println("Data is written to the file.");
// Closes the output stream
out.close();
}
}
In this example:
We create a PrintStream that is linked to the file output.txt. The println() method writes the string data to the file. The close() method closes the output stream. Output:
This is a line of text inside the file.
Methods of OutputStream:
The OutputStream class provides different methods that are implemented by its subclasses. Here are some of the methods:
void write(int b): Writes the specified byte to the output stream.
Syntax :public void write(int b) throws IOException
Parameters:
b - the byte
Throws:
IOException
Example:
We can use this method to write one specific byte to the OutputStream.
public static void fileOutputStreamByteSingle(String file, String data) throws IOException {
byte[] bytes = data.getBytes();
try (OutputStream out = new FileOutputStream(file)) {
out.write(bytes[6]);
}
}
If we call this method with data as “Hello World!”, what we get as result is a file with the following text. This, as we can see, is the seventh character of the string indexed sixth. void write(byte[] b): Writes array.length bytes from the specified array to the output stream.
Syntax :public void write(byte[] b) throws IOException
Parameters:
b - the data
Throws:
IOException