Curriculum
In Java, an OutputStream is an abstract class that represents an output stream of bytes. It is the superclass of all classes representing an output stream of bytes. The OutputStream class provides a standardized interface for writing data to different output destinations, such as files, network connections, and byte arrays. Here is an example of how the OutputStream class is used in Java:
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class OutputStreamExample { public static void main(String[] args) { try { OutputStream output = new FileOutputStream("output.txt"); String text = "Hello, world!"; byte[] bytes = text.getBytes(); output.write(bytes); output.close(); } catch (IOException e) { System.out.println("An error occurred while writing to the file: " + e.getMessage()); } } }
In this example, we create an OutputStream to a file named “output.txt”. We use the write()
method to write the bytes of a string to the output stream, and we close the stream using the close()
method.
The OutputStream class in Java has the following methods:
void write(int b) throws IOException
: Writes a byte of data to the output stream.void write(byte[] b) throws IOException
: Writes an array of bytes to the output stream.void write(byte[] b, int off, int len) throws IOException
: Writes a portion of an array of bytes to the output stream, starting at the specified offset off
and writing up to len
bytes.void flush() throws IOException
: Flushes the output stream, ensuring that all buffered data is written out to the destination.void close() throws IOException
: Closes the output stream and releases any system resources associated with it.Note that some classes that implement the OutputStream class, such as BufferedOutputStream and DataOutputStream, provide additional methods for writing data to the output stream in a more convenient way. For example, the DataOutputStream class provides methods for writing different types of primitive data types to the output stream, such as writeInt(int i)
and writeDouble(double d)
.