3. Input/Output Streams

3.1. Definition

A stream is a flowing sequence of characters.

  • A program can get input by reading characters from a stream attached to a source.

Figure 5.5. A stream of data entering a program.

A stream of data entering a program.

  • A program can produce output by writing characters to a stream attached to a destination.

  • Input and output sources can be anything that can contain data: a file, a string, or memory.

Figure 5.6. A stream of data leaving a program.

A stream of data leaving a program.

  • standard input: InputStream System.in

  • standard output: PrintStream System.out

  • standard error: PrintStream System.err

Figure 5.7. InputStream Class

InputStream Class

Figure 5.8. OutputStream Class

OutputStream Class

3.5.1. FileInputStream and FileOutputStream

Read data from or write data to a file on the native file system.

3.5.2. PipedInputStream and PipedOutputStream

Implement the input and output components of a pipe.

3.5.3. ByteArrayInputStream and ByteArrayOutputStream

Read data from or write data to a byte array in memory.

3.5.4. SequenceInputStream

Concatenate multiple input streams into one input stream.

3.5.5. StringBufferInputStream

Allow programs to read from a StringBuffer as if it were an input stream.

To use a filtered input (output) stream, you attach the filtered stream to another input (output) stream:

DataInputStream dis = new DataInputStream(System.in.read());
String input;
while ((input = dis.readLine()) != null) {
  . . . // do something interesting here }

DataInputStream and DataOutputStream

BufferedInputStream and BufferedOutputStream

LineNumberInputStream

PushbackInputStream

Byte pushback buffer

PrintStream

File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");

FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);

while ((c = fis.read()) != -1) {
   fos.write(c);
}
fis.close();
fos.close();

Audio in Portuguese