Writing Bytes to Output Streams

The fundamental method of the OutputStream class is write():

public abstract void write(int b) throws IOException

This method writes a single unsigned byte of data whose value should be between and 255. If you pass a number larger than 255 or smaller than zero, it’s reduced modulo 256 before being written.

Example 2.1, AsciiChart , is a simple program that writes the printable ASCII characters (32 to 126) on the console. The console interprets the numeric values as ASCII characters, not as numbers. This is a feature of the console, not of the OutputStream class or the specific subclass of which System.out is an instance. The write() method merely sends a particular bit pattern to a particular output stream. How that bit pattern is interpreted depends on what’s connected to the other end of the stream.

Example 2-1. The AsciiChart Program

import java.io.*;

public class AsciiChart {

  public static void main(String[] args) {
    
    for (int i = 32; i < 127; i++) {
      System.out.write(i);
      // break line after every eight characters.
      if (i % 8 == 7) System.out.write('\n');
      else System.out.write('\t');
    }
    System.out.write('\n');
   }
}

Notice the use of the char literals '\t' and '\n'. The compiler converts these to the numbers 9 and 10, respectively. When these numbers are written on the console, the console interprets those numbers as a tab and a linefeed, respectively. The same effect could have been achieved by writing the if clause like this:

if (i % 8 == 7) System.out.write(10); ...

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.