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.

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

try {<br />

byte[] b = new byte[100];<br />

int offset = 0;<br />

while (offset < b.length) {<br />

int bytesRead = System.in.read(b, offset, b.length - offset);<br />

if (bytesRead == -1) break; // end of stream<br />

offset += bytesRead;<br />

}<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println("Couldn't read from<br />

System.in!");}<br />

3.4 Counting the Available Bytes<br />

It's sometimes convenient to know how many bytes are available to be read before you<br />

attempt to read them. The InputStream class's available() method tells you how many<br />

bytes you can read without blocking. It returns if there's no data available to be read.<br />

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

For example:<br />

try {<br />

byte[] b = new byte[100];<br />

int offset = 0;<br />

while (offset < b.length) {<br />

int a = System.in.available();<br />

int bytesRead = System.in.read(b, offset, a);<br />

if (bytesRead == -1) break; // end of stream<br />

offset += bytesRead;<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println("Couldn't read from<br />

System.in!");}<br />

There's a potential bug in this code. There may be more bytes available than there's space in<br />

the array to hold them. One common idiom is to size the array according to the number<br />

available() returns, like this:<br />

try {<br />

byte[] b = new byte[System.in.available()];<br />

System.in.read(b);<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println("Couldn't read from<br />

System.in!");}<br />

This works well if you're only going to perform a single read. For multiple reads, however,<br />

the overhead of creating multiple arrays is excessive. You should probably reuse the array and<br />

only create a new array if more bytes are available than will fit in the array.<br />

The available() method in java.io.InputStream always returns 0. Subclasses are<br />

supposed to override it, but I've seen a few that don't. You may be able to read more bytes<br />

from the underlying stream without blocking than available() suggests; you just can't<br />

guarantee that you can. If this is a concern, you can place input in a separate thread so that<br />

blocked input doesn't block the rest of the program.<br />

45

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

Saved successfully!

Ooh no, something went wrong!