ptg7068951
284 HOUR 20: Reading and Writing Files
There are two kinds of streams:
. Input streams, which read data from a source
. Output streams, which write data to a source
All input and output streams are made up of bytes, individual integers
with values ranging from 0 to 255. You can use this format to represent
data, such as executable programs, word-processing documents, and MP3
music files, but those are only a small sampling of what bytes can repre-
sent.Abyte streamis used to read and write this kind of data.
A more specialized way to work with data is in the form of characters—
individual letters, numbers, punctuation, and the like. You can use a char-
acter stream when you are reading and writing a text source.
Whether you work with a stream of bytes, characters, or other kinds of
information, the overall process is the same:
. Create a stream object associated with the data.
. Call methods of the stream to either put information in the stream or
take information out of it.
. Close the stream by calling the object’s close()method.
Files
In Java, files are represented by the Fileclass, which also is part of the
java.iopackage. Files can be read from hard drives, CD-ROMs, and other
storage devices.
AFileobject can represent files that already exist or files you want to cre-
ate. To create a Fileobject, use the name of the file as the constructor, as in
this example:
File bookName = new File(“address.dat”);
This creates an object for a file named address.datin the current folder.
You also can include a path in the filename:
File bookName = new File(“data\\address.dat”);
When you have a Fileobject, you can call several useful methods on that
object:
. exists()—trueif the file exists, falseotherwise
. getName()—The name of the file, as a String
NOTE
Java class files are stored as
bytes in a form called bytecode.
The Java interpreter runs byte-
code,which doesn’t actually
have to be produced by the
Java language. It can run com-
piled bytecode produced by
other languages,including
NetRexx and Jython. You also
hear the Java interpreter
referred to as the bytecode
interpreter.
NOTE
This example works on a
Windows system,which uses
the backslash (\) character as
a separator in path and file-
names. Linux and other Unix-
based systems use a forward
slash (/) character instead. To
write a Java program that refers
to files in a way that works
regardless of the operating sys-
tem,use the class variable
File.pathSeparatorinstead of
a forward or backslash,as in
this statement:
File bookName = new
File(“data”+
File.pathSeparator
- “address.dat”);