23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 15.5. The cat Program<br />

import java.io.*;<br />

class Cat {<br />

}<br />

public static void main (String[] args) {<br />

String thisLine;<br />

// Loop across the arguments.<br />

for (int i=0; i < args.length; i++) {<br />

// Open the file for reading.<br />

try {<br />

BufferedReader br = new BufferedReader(new FileReader(args[i]));<br />

while ((thisLine = br.readLine()) != null) {<br />

System.out.println(thisLine);<br />

} // end while<br />

} // end try<br />

catch (<strong>IO</strong>Exception e) {System.err.println("Error: " + e);}<br />

} // end for<br />

} // end main<br />

15.8.3 Line Numbering<br />

<strong>Java</strong> I/O<br />

The java.io.LineNumberReader class is a subclass of java.io.BufferedReader that<br />

keeps track of which line you're currently reading. It has all the methods of BufferedReader,<br />

including readLine(). It also has methods to get and set the line number. This class replaces<br />

the deprecated java.io.LineNumberInputStream class.<br />

public class LineNumberReader extends BufferedReader<br />

There are two constructors in this class. Both chain this reader to an underlying reader; the<br />

second also sets the size of the buffer.<br />

public LineNumberReader(Reader in)<br />

public LineNumberReader(Reader in, int size)<br />

The LineNumberReader class overrides these six methods from its superclass,<br />

BufferedReader:<br />

public int read() throws <strong>IO</strong>Exception<br />

public int read(char[] text, int offset, int length) throws <strong>IO</strong>Exception<br />

public long skip(long n) throws <strong>IO</strong>Exception<br />

public void mark(int readAheadLimit) throws <strong>IO</strong>Exception<br />

public void reset() throws <strong>IO</strong>Exception<br />

public String readLine() throws <strong>IO</strong>Exception<br />

However, the changes are solely for the purpose of keeping track of the line number. They do<br />

not change the semantics of these methods at all. This class also introduces two methods:<br />

public void setLineNumber(int lineNumber)<br />

public int getLineNumber()<br />

377

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!