Writing Arrays of Bytes

It's often faster to write data in large chunks than it is to write it byte by byte. Two overloaded variants of the write( ) method do this:

public void write(byte[] data) throws IOException public void write(byte[] data, int offset, int length) throws IOException

The first variant writes the entire byte array data. The second writes only the subarray of data starting at offset and continuing for length bytes. For example, the following code fragment blasts the bytes in a string onto System.out:

String s = "How are streams treating you?"; byte[] data = s.getBytes( ); System.out.write(data);

Conversely, you may 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 1024, 2048, or 4096 bytes. Network connections often require smaller buffer sizes128 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 1024 bytes for files.

Example 2-2 is a simple program that constructs a byte array filled with an ASCII chart, then blasts it onto the console in one call to write( ).

Example 2-2. The AsciiArray program

import java.io.*; public class AsciiArray { public static void main(String[] args) { byte[] b = new byte[(127-31)*2]; int index = 0; for (int i = 32; i < 127; i++) { b[index++] = (byte) i; // Break line after every eight characters. if (i % 8 == 7) b[index++] = (byte) ' '; else b[index++] = (byte) ' '; } b[index++] = (byte) ' '; try { System.out.write(b); } catch (IOException ex) { System.err.println(ex); } } }

The output is the same as in Example 2-1. Because of the nature of the console, this particular program probably isn't a lot faster than Example 2-1, but it certainly could be if you were writing data into a file rather than onto the console. The difference in performance between writing a byte array in a single call to write( ) and writing the same array by invoking write( ) once for each component of the array can easily be a factor of a hundred or more.

Категории