Home Java Java-tips Summaries Summary: I/O

Ask Questions?

View Latest Questions



Summary: I/O
Posted on: July 27, 2006 at 12:00 AM
Some System methods are relevant to I/O

Java: Summary: I/O

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 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.newLine();   // adds newline character(s)


} catch (IOException e) { 

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