13.07.2015 Views

I/O Fundamentals

I/O Fundamentals

I/O Fundamentals

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Java Input and OutputTracking Line NumbersThe creators of Java realized that System.out and System.err would be veryheavily used, and did not want to force inclusion of exception handling every timeyou wanted to write System.out.println(4).Therefore, PrintStream and PrintWriter catch their own exceptions and set anerror flag. If you are using one of these classes for real output in your program(not merely using System.out.println()) you should call checkError() to seeif an error has occurred.Because of this behavior, PrintStream and PrintWriter are not well suited foruse other than System.out and System.err!A common task is to keep track of which line number is being read. Working thisinto the Java filter model is simple!The core Java API defines two classes to perform this task:LineNumberInputStream and LineNumberReader.LineNumberInputStream has been deprecated because it assumes that a byte issufficient to represent a character. Do not use LineNumberInputStream! Thatsaid, we have less to discuss.LineNumberReader is a filter that tracks how many "new line" sequences ("\n","\r", or "\r\n") have been encountered while reading from its inputDelegate. Thisclass implements its own buffer; you do not need to wrap it in aBufferedReader.After reading any text from a LineNumberReader (for example, calling itsreadLine() method), you can call its getLineNumber() method to the currentline number. You can interpret this line number in two ways:• the line number of the next character to read, based at "line 0"• the line number of the last newline read, based at "line 1"If you need to know the line number before you have read characters on that line,you'll probably want to add "1" to the line number returned. If you don't need theline number until after reading the line, the line number is fine "as is". An exampleof using the line number after reading the line:import java.io.*;Java Input and Output -26© 1996-2003 jGuru.com. All Rights Reserved.

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

Saved successfully!

Ooh no, something went wrong!