Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O

Similar presentations


Presentation on theme: "Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O"— Presentation transcript:

1 Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O
By: Anupam Chanda

2 Today’s Menu Introduction to I/O Streams Reader and Writer Classes
StreamTokenizer and Parsing Command-line Arguments System Class

3 Stream I/O Stream – abstract concept of input and output
Sequence of data Has a source or a destination java.io package

4 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);

5 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

6 Reader and Writer

7 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

8 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

9 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(); }

10

11

12 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

13 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(); }

14 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


Download ppt "Comp 212: Intermediate Programming Lecture 30 – Stream and File I/O"

Similar presentations


Ads by Google