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


Readers, Writers and Streams

I/O classes divided into:

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]