English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about Java OutputStream and its methods through an example.
The OutputStream class in the java.io package is an abstract superclass that represents a byte output stream.
Since OutputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.
To use the features of OutputStream, we can use its subclasses. Some of them are:
In the next tutorial, we will learn about all these subclasses.
To create an OutputStream, we must first import the java.io.OutputStream package. After importing the package, we can create an output stream.
//Create an OutputStream OutputStream object = new FileOutputStream();
Here, we have created an output stream object FileOutputStream. Since OutputStream is an abstract class, we cannot create an object of OutputStream.
Note: We can also create output streams from other subclasses of the OutputStream class.
The OutputStream class provides various methods implemented by its subclasses. The following are some of them:
write() - Write the specified bytes into the output stream
write(byte[] array) - Write the bytes from the specified array into the output stream
flush() - Force all existing data in the output stream to be written to the target
close() - Close the output stream
Below is the method implemented by the FileOutputStream class using OutputStream.
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 within the file."; try { OutputStream out = new FileOutputStream("output.txt"); //Convert a string to bytes byte[] dataBytes = data.getBytes(); //Write data to the output stream out.write(dataBytes); System.out.println("Data has been written to the file."); //Close the output stream out.close(); } catch (Exception e) { e.getStackTrace(); } } }
In the above example, we used the FileOutputStream class to create an output stream. Now, the output stream is connected to the fileoutput.txtLink.
OutputStream out = new FileOutputStream("output.txt");
To write data tooutput.txtThe file, we have implemented these methods.
output.write(); //Write data to the file output.close(); //Close the output stream
When we run the program,output.txtThe file will be written with the following content.
This is a line of text within the file.