Java Streams   «Prev  Next»

Lesson 2Writing data to a stream
Objective Explore how output streams work.

Writing Data to Stream in Java

So far this course has concentrated on input streams. Output streams are equally important, and often easier to work with. Where input streams take bytes from an outside source and bring them into a Java program, output streams send bytes generated by a Java program to an outside destination. Like input streams, output streams transmit bytes in a certain irreversible order. java.io.OutputStream is the abstract superclass that all output streams extend. It has methods for writing bytes, writing arrays of bytes, flushing streams, and closing streams. The write() methods should look familiar.

Java OutputStream's write() methods

public abstract void write(int b) throws IOException
public void write(byte b[]) throws IOException
public void write(byte b[], int offset, int length) throws IOException

Subclasses must implement the abstract write(int b) method. They often choose to override the third variant,
write(byte[], data int offset, int length), 

for reasons of performance. The implementation of the three-argument version of the write() method in OutputStream simply invokes write(int b) repeatedly; that is:

public void write(byte[] data, int offset, int length) throws IOException {
 for (int i = offset; i < offset+length; i++) 
  write(data[i]);
}

Most subclasses can provide more efficient implementations of this method. The one argument variant of write() merely invokes write(data, 0, data.length); if the three argument variant has been overridden, this method will perform reasonably well. However, a few subclasses may override it anyway. They are mirror images of the read() methods in the InputStream class. The close()method should also be familiar. It is used the same way as the close() method in the InputStream class, only on output streams.

public void close() throws IOException

OutputStream is Abstract Class

Like InputStream, OutputStream is an abstract class that is subclassed to handle particular types of streams. For example, the FileOutputStream class writes data to a file. System.out is an output stream connected to the console. Although the write() method is declared abstract, all the concrete subclasses of OutputStream you will actually be dealing with do implement it. Because OutputStream is abstract, you can never instantiate it directly; you can only instantiate its subclasses.