Chapter 19. Streams and Binary Input/Output


  • To become familiar with the concepts of text and binary formats

  • To learn about encryption

  • To understand when to use sequential and random file access

  • To be able to read and write objects using serialization

In this chapter you will learn more about how to write Java programs that interact with disk files and other sources of bytes and characters. You will learn about text and binary formats, and about sequential and random access to the data in a file. We will discuss how you can use object serialization to save and load complex objects with very little effort. As an application of file processing, you will study a program for encrypting and decrypting sensitive data.

Readers, Writers, and Streams

There are two fundamentally different ways to store data: in text format or binaryformat. In text format, data items are represented in human-readable form, as a sequence of characters. For example, in text form, the integer 12,345 is stored as the sequence of five characters:

'1' '2' '3' '4' '5'

In binary form, data items are represented in bytes. A byte is composed of 8 bitsand can denote one of 256 values. For example, in binary format, the integer 12,345 is stored as a sequence of four bytes:

0 0 48 57

(because 12,345 = 48 • 256 + 57).

The Java library provides two sets of classes for handling input and output. Streams handle binary data. Readers and writers handle data in text form. Figure 1 shows a part of the hierarchy of the Java classes ...

Get Big Java, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.