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.

public class RandomInputStream extends InputStream {<br />

}<br />

private transient Random generator = new Random();<br />

public int read() {<br />

}<br />

int result = generator.nextInt() % 256;<br />

if (result < 0) result = -result;<br />

return result;<br />

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

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

}<br />

byte[] temp = new byte[length];<br />

generator.nextBytes(temp);<br />

System.arraycopy(temp, 0, data, offset, length);<br />

return length;<br />

public int read(byte[] data) throws <strong>IO</strong>Exception {<br />

}<br />

generator.nextBytes(data);<br />

return data.length;<br />

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

}<br />

// It's all random so skipping has no effect.<br />

return bytesToSkip;<br />

The no-argument read() method returns a random int in the range of an unsigned byte (0 to<br />

255). The other two read() methods fill a specified part of an array with random bytes. They<br />

return the number of bytes read (in this case the number of bytes created).<br />

3.9 An Efficient Stream Copier<br />

As a useful example of both input and output streams, in Example 3.3 I'll present a<br />

StreamCopier class that copies data between two streams as quickly as possible. (I'll reuse<br />

this class in later chapters.) This method reads from the input stream and writes onto the<br />

output stream until the input stream is exhausted. A 256-byte buffer is used to try to make the<br />

reads efficient. A main() method provides a simple test for this class by reading from<br />

System.in and copying to System.out.<br />

Example 3.3. The StreamCopier Class<br />

package com.macfaq.io;<br />

import java.io.*;<br />

48

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

Saved successfully!

Ooh no, something went wrong!