Previous | Next | Trail Map | Writing Java Programs | Input and Output Streams

Using Streams to Read and Write Files (1.1notes)

File streams are perhaps the easist streams to understand. Simply put, FileInputStream(in the API reference documentation) ( FileOutputStream(in the API reference documentation)) represents an input (output) stream on a file that lives on the native file system. You can create a file stream from the filename, a File(in the API reference documentation) object, or a FileDescriptor(in the API reference documentation) object. Use file streams to read data from or write data to files on the file system.

This small example uses two file streams to copy the contents of one file into another:


class FileStreamsTest {
    public static void main(String[] args) {
        try {
            File inputFile = new File("farrago.txt");
            File outputFile = new File("outagain.txt");

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

            while ((c = != -1) {

        } catch (FileNotFoundException e) {
            System.err.println("FileStreamsTest: " + e);
        } catch (IOException e) {
            System.err.println("FileStreamsTest: " + e);
Here are the contents of the input file farrago.txt:
So she went into the garden to cut a cabbage-leaf, to
make an apple-pie; and at the same time a great
she-bear, coming up the street, pops its head into the
shop. 'What! no soap?' So he died, and she very
imprudently married the barber; and there were
present the Picninnies, and the Joblillies, and the
Garyalies, and the grand Panjandrum himself, with the
little round button at top, and they all fell to playing
the game of catch as catch can, till the gun powder ran
out at the heels of their boots.

Samuel Foote 1720-1777
The FileStreamsTest program creates a FileInputStream from a File object with this code:
File inputFile = new File("farrago.txt"); 
FileInputStream fis = new FileInputStream(inputFile);
Note the use of the File object, inputFile, in the constructor. inputFile represents the named file, farrago.txt, on the native file system. This program only uses inputFile to create a FileInputStream on farrago.txt. However, the program could use inputFile to get information about farrago.txt such as its full path name.

Previous | Next | Trail Map | Writing Java Programs | Input and Output Streams