- classes that your programs can use to read and to write data
- I/O Stream
- to input is to open a stream on an information source (a file, memory, a socket) and read the data (16 bits character or a byte)
- Character Input Streams (public abstract class Reader)
java.lang.Object
|
+--java.io.Reader
|
+--BufferedReader, CharArrayReader, FilterReader,
InputStreamReader, PipedReader, StringReader
- to output is to open a stream to a destination and write the data
- Character Output Streams (public abstract class Writer)
java.lang.Object
|
+--java.io.Writer
|
+--BufferedWriter, CharArrayWriter, FilterWriter,
OutputStreamWriter, PipedWriter, PrintWriter,
StringWriter
- to read and write 8-bit bytes, programs should use the byte streams which are subclass of the abstract InputStream and OutputStream class
- input examples
BufferedReader br;
String s;
br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine(); // read one line from console
br = new BufferedReader(new FileReader("filename"));
s = br.readLine(); // read one line from a file
br = new BufferedReader(new
StringReader("This is a string\nwith two lines.");
s = br.readLine(); // read one line from a string
// (the string resides in
// the StringReader object)
- output examples
PrintWriter pw;
String s = "A line of text.";
pw = new PrintWriter(System.out, true);
pw.println(s); // print one line to console
pw = new PrintWriter(new FileWriter("filename"));
pw.println(s); // print one line to a file
StringWriter sw;
pw = new PrintWriter(sw = new StringWriter());
pw.println(s); // print one line to a string
// (the string resides in
// the StringWriter object)
PrintWriter pw = new PrintWriter(sw);
pw.print("Hello");
pw.print(", there!");
pw.flush();
stdOut.println(sw.toString());
- The java.io.StreamTokenizer
- is more powerful and general than the java.util.StringTokenizer
- parses streams instead of strings
- each token is automatically converted to either a double, or a String
- the
ttype, nval, and sval
fields of StreamTokenizer
- example
String s = "12 this that 52.7 hey5"
StreamTokenizer st = new
StreamTokenizer(new StringReader(s));
int nums = 0, words = 0;
st.nextToken(); // could throw IOException
while (st.ttype != st.TT_EOF) {
switch (st.ttype) {
case st.TT_NUMBER:
++nums;
break;
case st.TT_WORD:
++words;
break;
}
st.nextToken(); // could throw IOException
}
stdOut.println("In string: " + s);
stdOut.println("Number of numbers: " + nums +
", number of words: " + words);
The output follows.
In string: 12 this that 52.7 hey5
Number of numbers: 2, number of words: 3