Java Streams  «Prev  Next»

Lesson 5Other sources of input and output streams
Objective Investigate input and output streams from files, network connections, and programs.

Input and Output Streams in Java

Besides System.in and System.out, the other sources of data in a Java program include files, network connections, and other programs. These other data sources are also provided as input or output streams.

Files

Files, whatever their contents, are read and written through input and output streams.
  1. The java.io.FileInputStream class is used to read a file.
  2. The java.io.FileOutputStream class is used to write a file.

FileInputStream and FileOutputStream

Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. Although both classes support additional constructors, the following are the forms that we will be using:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException

Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be opened or created, then FileNotFoundException is thrown. FileNotFoundException is a subclass of IOException. When an output file is opened, any preexisting file by the same name is destroyed.


Until now I have used the streams System.in and System.out. These are convenient for examples, but in real life, you will more commonly attach streams to data sources like files and network connections. You will use the
  1. java.io.FileInputStream and
  2. java.io.FileOutputStream
classes, which are concrete subclasses of java.io.InputStream and java.io.OutputStream, to read and write files.
FileInputStream and FileOutputStream provide input and output streams that let you read and write files. These classes do not provide a mechanism for filespecific operations, like finding out whether a file is readable or writable.

Network connections

Network connections are also a fertile source of streams. When you connect to an Internet server, you read the data the server sends you via an input stream, and you send data back to the server via an output stream.

Java Programs

Java programs themselves produce streams.
  1. ByteArrayInputStreams
  2. ByteArrayOutputStreams
  3. StringBufferInputStreams
  4. PipedInputStreams, and
  5. PipedOutputStreams
all use the stream metaphor to move data from one part of a Java program to another.

Network connections

Network connections are also a fertile source of streams. When you connect to an Internet server, you read the data the server sends you via an input stream, and you send data back to the server via an output stream.