O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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++] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required