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


Using Streams to Read and Write Files

File streams are perhaps the easist streams to understand. Simply put, FileInputStream(in the API reference documentation)(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 the file streams to copy the contents of one file into another:

import java.io.*;

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 = fis.read()) != -1) {
               fos.write(c);
            }

            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            System.err.println("FileStreamsTest: " + e);
        } catch (IOException e) {
            System.err.println("FileStreamsTest: " + e);
        }
    }
}
Here's 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.

See Also

java.io.FileInputStream
java.io.FileOutputStream


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