Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O By: Anupam Chanda
Today’s Menu Introduction to I/O Streams Reader and Writer Classes StreamTokenizer and Parsing Command-line Arguments System Class
Stream I/O Stream – abstract concept of input and output Sequence of data Has a source or a destination java.io package
Reading and Writing open(stream); while (more info) read(stream); WRITE open(stream); while (more info) read(stream); close(stream); open(stream); while (more info) write(stream); close(stream);
Types of Streams Byte Streams Character Streams Operate on bytes (8-bit) No further discussion Character Streams Operate on 16-bit characters Reader and Writer
Reader and Writer
Reader An abstract class Need a concrete subclass Can read from an abstract character source Need a concrete subclass Read from a concrete character source FileReader fReader = new FileReader(fileName); fReader.read() – next character from source
Writer An abstract class Need a concrete subclass Can write to an abstract character destination Need a concrete subclass Write to a concrete character source FileWriter fWriter = new FileWriter(fileName); fWriter.write() – next character to destination
Read and Write Text Files import java.io.*; public class Copy { public static void main(String[] args) throws IOException { FileReader in = new FileReader(“in.txt”); FileWriter out = new FileWriter(“out.txt”); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
StreamTokenizer and Parsing Parse an input stream of characters Identify words, numbers, etc. Tokenizing – breaking an input stream in “tokens” int k = 100; Tokens – “int”, “k”, “=“, “100”, “;” java.io.StreamTokenizer Example program on web page
Command-line arguments Pass arguments to the program at run-time public static void main(String[] argv) { for(int j = 0; j < argv.length; j++) System.out.print(argv[j] + “ "); System.out.println(); }
Stdin, Stdout & Stderr System.out.println(“Hello world!”); System.out – PrintStream object Writes to standard output (stdout) – monitor % java MyClass > out.txt System.in – stdin (keyboard) % java MyClass < in.txt System.err – stderr (monitor) % java MyClass >& err.txt PrintStream is deprecated