In this tutorial, we will learn about the Java OutputStream and its methods with the help of an example.
The OutputStream class of the java.io package is an abstract superclass that represents an output stream of bytes.
Since OutputStream is an abstract class, it isn’t valuable without anyone else. In any case, its subclasses can be used to write data.
In this article, you will learn-
Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some of them are:
We will learn about all these subclasses in the next tutorial.
Make an OutputStream
To make an OutputStream, we should import the java.io.OutputStream package first. When we import the package, here is the manner by which we can make the output stream.
// Creates an OutputStream
OutputStream object = new FileOutputStream();
Here, we have made an object of output stream using FileOutputStream. It is on the grounds that OutputStream is an abstract class, so we can’t make an object of OutputStream.
Note: We can likewise make the output stream from different subclasses of the OutputStream class.
Methods of OutputStream
The OutputStream class gives various techniques that are executed by its subclasses. Here are a portion of the strategies:
- write() – writes the specified byte to the output stream
- write(byte[] array) – writes the bytes from the specified array to the output stream
- flush() – forces to write all data present in output stream to the destination
- close() – closes the output stream
Example: OutputStream Using FileOutputStream
Here is how we can implement OutputStream using the FileOutputStream class.
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);
System.out.println("Data is written to the file.");
// Closes the output stream
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have made an output stream using the FileOutputStream class. The output stream is presently connected with the file output.txt.
OutputStream out = new FileOutputStream("output.txt");
To write data to the output.txt file, we have implemented these methods.
output.write(); // To write data to the file
output.close(); // To close the output stream
When we run the program, the output.txt file is filled with the following content.
This is a line of text inside the file.
To learn more, visit Java OutputStream (official Java documentation).
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.