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 StreamCopier {<br />

}<br />

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

try {<br />

}<br />

}<br />

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

public static void copy(InputStream in, OutputStream out)<br />

throws <strong>IO</strong>Exception {<br />

}<br />

// Do not allow other threads to read from the input<br />

// or write to the output while copying is taking place<br />

synchronized (in) {<br />

synchronized (out) {<br />

byte[] buffer = new byte[256];<br />

while (true) {<br />

int bytesRead = in.read(buffer);<br />

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

out.write(buffer, 0, bytesRead);<br />

}<br />

}<br />

}<br />

Here's a simple test run:<br />

D:\JAVA\ioexamples\03>java com.macfaq.io.StreamCopier<br />

this is a test<br />

this is a test<br />

0987654321<br />

0987654321<br />

^Z<br />

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

Input was not fed from the console (DOS prompt) to the StreamCopier program until the end<br />

of each line. Since I ran this in Windows, the end-of-stream character is Ctrl-Z. On Unix it<br />

would have been Ctrl-D.<br />

49

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

Saved successfully!

Ooh no, something went wrong!