Previous


1.1 Changes: File I/O

The FileStreams example highlights the FileInputStream and FileOutputStream classes. JDK 1.1 introduces two new classes, FileReader(in the API reference documentation) and FileWriter(in the API reference documentation), that perform the same function as FileInputStream and FileOutputStream only they work with characters rather than bytes. Generally speaking, it is best to use the new character-streams.

Here's the FileStreams example rewritten to use FileReader and FileWriter classes instead of FileInputStream and FileOutputStream:

FileStreamsTest.java

import java.io.*;

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

            FileReader fr = new FileReader(inputFile);
            FileWriter fw = new FileWriter(outputFile);
            int c;

            while ((c = fr.read()) != -1) {
               fw.write(c);
            }

            fr.close();
            fw.close();
        } catch (FileNotFoundException e) {
            System.err.println("FileStreamsTest: " + e);
        } catch (IOException e) {
            System.err.println("FileStreamsTest: " + e);
        }
    }
}


Previous