Java Lecture 3
[Previous Lecture]
[Lecture Index]
[Next Lecture]
LineNum.java
import java.io.*;
class LineNum {
public static void main(String av[]) {
try {
// Class that allows reading of a line
BufferedReader br;
String line;
int lineNo = 1;
// Create instance tied to std input
// (InputStreamReader is needed glue)
br = new BufferedReader(new InputStreamReader(System.in));
// readLine returns null at end of file
while ((line = br.readLine()) != null)
{
System.out.println(lineNo + ": " + line);
lineNo++;
}
}
// Creating and using input streams/readers
// may throw IO exceptions, so catch them
catch (IOException e) {
System.out.println("Error reading standard input");
}
}
}
General Design of Java's I/O System
- Consists of many (many) classes
- Classes live in java.io
- Instances of these are chained together
- For input:
- usually one `source'
- any number of `filters' stacked on top
Example:
InputStream | a `source' (e.g., System.in) |
InputStreamReader | filter: converts bytes to chars |
BufferedReader | filter: reads in large chunks, provides readLine() |
- for output
- usually one `destination'
- any number of `filters' stacked on top
Example:
FileWriter | a `destionation' (opens file for writing) |
BufferedWriter | filter: writes in large chunks |
PrintWriter | filter: provides println(), etc. |
Readers, Writers and Streams
I/O classes divided into:
- Readers, Writers: for unicode character I/O
Examples:
FileReader | source: reads from named file |
StringArrayReader | source: reads from String |
CharArrayReader | source: reads from char[] |
InputStreamReader | filter: converts from Stream to Reader |
BufferedReader | filter: reads in large chunks |
LineNumberReader | filter: counts line numbers |
PushbackReader | filter: allows `unreading' |
- InputStreams, OutputStreams: for binary data
Examples:
FileInputStream | source: reads from named file |
ByteArrayInputStream | source: reads from char[] |
BufferedInputStream | filter: reads in large chunks |
PushbackInputStream | filter: allows `unreading' |
- System.out is a PrintStream - backwards compatibility
AddLineNum.java
import java.io.*;
class AddLineNum {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++) {
try {
FileReader fr = new FileReader(args[i]);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(args[i] + ".xxx");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
String line;
int lineNum = 1;
while ((line = br.readLine()) != null)
{
pw.println(lineNum + ": " + line);
lineNum++;
}
pw.close();
br.close();
} catch (FileNotFoundException e) {
System.err.println("Can't open " + args[i]);
} catch (IOException e) {
System.err.println("IO error processing " + args[i] + ": "
+ e.getMessage());
}
}
}
}
[Previous Lecture]
[Lecture Index]
[Next Lecture]