Simple Java I/O: General Principles
Simple Java I/O: General Principles
Part I
General Principles
2
Streams
3
How to do I/O
import java.io.*;
4
open
use
Why Java I/O is hard close
5
open
use
Opening a stream close
6
open
use
Example of opening a stream close
7
open
use
Using a stream close
8
open
use
Example of using a stream close
int charAsInt;
charAsInt = fileReader.read( );
9
open
use
Manipulating the input data close
10
open
use
Reading lines close
String s;
s = bufferedReader.readLine( );
11
open
use
Closing close
Part II
LineReader and LineWriter
14
My LineReader class
class LineReader {
BufferedReader bufferedReader;
15
Basics of the LineReader constructor
Create a FileReader for the named file:
FileReader fileReader =
new FileReader(fileName);
16
The full LineReader constructor
LineReader(String fileName) {
FileReader fileReader = null;
try { fileReader = new FileReader(fileName); }
catch (FileNotFoundException e) {
System.err.println
("LineReader can’t find input file: " + fileName);
e.printStackTrace( );
}
bufferedReader = new BufferedReader(fileReader);
}
17
readLine
String readLine( ) {
try {
return bufferedReader.readLine( );
}
catch(IOException e) {
e.printStackTrace( );
}
return null;
}
18
close
void close() {
try {
bufferedReader.close( );
}
catch(IOException e) { }
}
19
How did I figure that out?
I wanted to read lines from a file
I thought there might be a suitable readSomething method, so
I went to the API Index
Note: Capital letters are all alphabetized before lowercase in the Index
I found a readLine method in several classes; the most
promising was the BufferedReader class
The constructor for BufferedReader takes a Reader as an
argument
Reader is an abstract class, but it has several implementations,
including InputStreamReader
FileReader is a subclass of InputStreamReader
There is a constructor for FileReader that takes as its
argument a (String) file name
20
The LineWriter class
class LineWriter {
PrintWriter printWriter;
21
The constructor for LineWriter
LineWriter(String fileName) {
try {
printWriter =
new PrintWriter(
new FileOutputStream(fileName), true);
}
catch(Exception e) {
System.err.println("LineWriter can’t " +
"use output file: " + fileName);
}
}
22
Flushing the buffer
23
PrintWriter
24
writeLine
25
close
void close( ) {
printWriter.flush( );
try {
printWriter.close( );
}
catch(Exception e) { }
}
26