Java Reference
In-Depth Information
Loading, saving
and displaying text
10
In this chapter we begin to describe how graphical interfaces are used to display
and manipulate text. We introduce the methods for reading and writing text files
and for displaying text.
10.1
Reading and writing text files
A text in Java is a sequence of characters in Unicode format. The Unicode char-
acter set contains more than 16,000 characters, including Japanese and Chinese
ones. Every Unicode character is stored in 2 bytes (16 bit). Most text files contain
!
data in ASCII format, which can express at most 256 characters and needs one
byte (8 bit) to store one character. Depending on the format of the text file an ap-
propriate way must be used to read or write it. If one reads an ASCII file as though
it were a Unicode file then two consecutive ASCII characters are interpreted as
one Unicode character. This looks funny but is not what we want. Nowadays, most
text files are in ASCII format. Let us briefly look at how data transfer is handled
in Java.
Input and output in Java are based on the concept of a data stream . Such a
data stream is a sequence of characters (or other data objects). One distinguishes
between an input stream from which one can extract (read) data and an output
stream to which one can append (write) data. Streams are not limited to reading
data from the hard disk. They can also be used to exchange data with the internet
or with another application.
The data in a stream do not have to be human-readable text. There are streams
in Java that consist of doubles or integers in binary representation. To extract data
from a stream in the appropriate form (or to add it) one uses so-called filters . The
stream is sent through a filter designed to handle the specific data format of this
stream. The filter then extracts and interprets the data in the desired way. The
names of filters for ASCII data streams end with Reader (input) or Writer (output).
The java.io library supplies the necessary classes and methods for file han-
dling. The library is included by
import java.io.*;
Search WWH ::




Custom Search