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.

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

Astute readers will have noticed that Example 2.1 did not actually catch any <strong>IO</strong>Exceptions.<br />

The PrintStream class, of which System.out is an instance, overrides write() with a<br />

variant that does not throw <strong>IO</strong>Exception.<br />

2.3 Writing Arrays of Bytes<br />

It's often faster to write larger chunks of data than to write byte by byte. Two overloaded<br />

variants of the write() method do this:<br />

public void write(byte[] data) throws <strong>IO</strong>Exception<br />

public void write(byte[] data, int offset, int length) throws <strong>IO</strong>Exception<br />

The first variant writes the entire byte array data. The second writes only the sub-array of<br />

data starting at offset and continuing for length bytes. For example, the following code<br />

fragment blasts the bytes in a string onto System.out:<br />

String s = "How are streams treating you?";<br />

byte[] data = s.getBytes();<br />

System.out.write(data);<br />

Conversely, you may run into performance problems if you attempt to write too much data at<br />

a time. The exact turnaround point depends on the eventual destination of the data. Files are<br />

often best written in small multiples of the block size of the disk, typically 512, 1024, or 2048<br />

bytes. Network connections often require smaller buffer sizes, 128 or 256 bytes. The optimal<br />

buffer size depends on too many system-specific details for anything to be guaranteed, but I<br />

often use 128 bytes for network connections and 1024 bytes for files.<br />

Example 2.2 is a simple program that constructs a byte array filled with an ASCII chart, then<br />

blasts it onto the console in one call to write().<br />

Example 2.2. The AsciiArray Program<br />

import java.io.*;<br />

public class AsciiArray {<br />

}<br />

}<br />

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

byte[] b = new byte[(127-31)*2];<br />

int index = 0;<br />

for (int i = 32; i < 127; i++) {<br />

b[index++] = (byte) i;<br />

// Break line after every eight characters.<br />

if (i % 8 == 7) b[index++] = (byte) '\n';<br />

else b[index++] = (byte) '\t';<br />

}<br />

b[index++] = (byte) '\n';<br />

try {<br />

System.out.write(b);<br />

}<br />

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

36

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

Saved successfully!

Ooh no, something went wrong!