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

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

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

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

}<br />

}<br />

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

}<br />

}<br />

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

A sample run follows. Notice the deprecation warning when this code is compiled.<br />

DataInputStream's readLine() method is one of the most common sources of deprecation<br />

warnings in <strong>Java</strong> 1.1.<br />

% javac Echo.java<br />

Note: Echo.java uses a deprecated API. Recompile with "-deprecation" for<br />

details.<br />

1 warning<br />

% java Echo<br />

This is a test<br />

This is a test<br />

This is another test<br />

This is another test<br />

Hello<br />

Hello<br />

Goodbye Now<br />

Goodbye Now<br />

.<br />

%<br />

Although we won't officially take up readers until Chapter 15, it's not very hard to rewrite this<br />

program so that it doesn't generate deprecation warnings. All you need to do is replace<br />

DataInputStream with BufferedReader chained to an InputStreamReader. Example 7.7<br />

demonstrates.<br />

Example 7.7. The ReaderEcho Program<br />

import java.io.*;<br />

public class ReaderEcho {<br />

}<br />

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

}<br />

try {<br />

BufferedReader din = new BufferedReader<br />

(new InputStreamReader(System.in), 1);<br />

while (true) {<br />

String theLine = din.readLine();<br />

if (theLine == null) break; // end of stream<br />

if (theLine.equals(".")) break; // . on line by itself<br />

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

}<br />

}<br />

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

This only works (and is only needed) for readLine(). BufferedReader does not have<br />

equivalents for the rest of the DataInputStream methods like readFully(), but more details<br />

will wait until Chapter 15.<br />

110

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

Saved successfully!

Ooh no, something went wrong!