Java: Summary: I/O

This needs a lot of work!!!!!!!!!!! Related classes: File, BufferedReader, ....
System Methods
Some System methods are relevant to I/O
String System.getProperty("user.dir") Returns the path to the current directory (ie, the value of ".").

File Methods

These are some of the most common File methods. In all of these prototypes, i and j are int, s and t are Strings, and c is a char.
booleanf.exists() true if file exists.
booleanf.isFile() true if its a file.
booleanf.isDirectory() true if its a directory.
String f.getName() returns name of file/directory.
String f.getPath() returns path of file/directory.
File[] File.listRoots() [Java 2] list of file system roots, eg, A:, C:, ....

BufferedReader/BufferedWriter Methods

java.io.BufferedReader and java.io.BufferedWriter are used to read/write Strings from/to text files.
Constructors -- see example below
BufferedReader Methods
Stringbr.readLine() Returns next input line without newline char(s) or null if no more input. May throw IOException.
Stringbr.close() Should close when finished reading.
BufferedWriter Methods
voidbw.writeLine(s) Writes s to file without newline char(s). May throw IOException.
Stringbw.close() MUST close when finished writing.

Example

// Example reads from from one file and writes to another.
// Assume inFile and outFile are Strings with path/file names.
try { 
    BufferedReader bufReader = new BufferedReader(new FileReader(inFile)); 
    BufferedWriter bufWriter = new BufferedWriter(new FileWriter(outFile)); 

    String line = null; 
    while ((line=bufReader.readLine()) != null){ 
        bufWriter.write(line); 
        bufWriter.newLine();   // adds newline character(s)
    } 

    bufReader.close(); 
    bufWriter.close(); 

} catch (IOException e) { 
    System.err.println(e); 
    System.exit(1); 
}

Copyright 1999 Fred Swartz Last update: 2000-02-30