Writing Arrays of Bytes

It’s often faster to write larger chunks of data than to write 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 sub-array 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 512, 1024, or 2048 bytes. Network connections often require smaller buffer sizes, 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 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++] ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.