Java Streams   «Prev  Next»

Lesson 5 Writing bytes
ObjectiveWrite a program that copies data from System.in to System.out with maximum efficiency.
It is often faster to write larger chunks of data at a time, rather than writing byte by byte. Two polymorphic variants of write() method do this. The following code fragment blasts the bytes in a string onto System.out:
String s = "How are streams treating you?";
byte[] b = s.getBytes();
System.out.write(b); 

You can also run into performance problems if you attempt to write too much data at a time. The exact turnaround point depends on the eventual destination of the data.
Files are often best written in small multiples of the block size of the disk, typically 512; 1,024; or 2,048 bytes. Network connections often require smaller buffer sizes, typically 128 or 256 bytes. The optimal buffer size depends on too many system-specific details for anything to be guaranteed, but I often use 128 bytes for network connections and 1,024 bytes for files.

Writing Java Bytes - Exercise

Click the Exercise link below to write a program that reads data from System.in into a byte array buffer, then copies the data onto System.out.
Writing Java Bytes - Exercise