AhmadLang / Java, How To Program, 2004
.pdf
Method getFile is defined in lines 3862 of Fig. 14.37. Line 41 creates a JFileChooser and assigns its reference to fileChooser. Lines 4243 call method setFileSelectionMode to specify what the user can select from the fileChooser. For this program, we use JFileChooser static constant
FILES_AND_DIRECTORIES to indicate that files and directories can be selected. Other static constants include FILES_ONLY and DIRECTORIES_ONLY.
Line 45 calls method showOpenDialog to display the JFileChooser dialog titled Open. Argument this specifies the JFileChooser dialog's parent window, which determines the position of the dialog on the screen. If null is passed, the dialog is displayed in the center of the screenotherwise, the dialog is centered over the application window (specified by the argument this). A JFileChooser dialog is a modal dialog that does not allow the user to interact with any other window in the program until the user closes the JFileChooser by clicking the Open or Cancel button. The user selects the drive, directory or file name, then clicks Open. Method showOpenDialog returns an integer specifying which button ( Open or Cancel) the user clicked to close the dialog. Line 48 tests whether the user clicked Cancel by comparing the result with static constant CANCEL_OPTION. If they are equal, the program terminates. Line 51 retrieves the file the user selected by calling JFileChooser method getSelectedFile. The program then displays information about the selected file or directory.
[Page 733]
14.10. Wrap-Up
In this chapter, you learned how to use file processing to manipulate persistent data. You learned that data is stored in computers as 0s and 1s, and that combinations of these values are used to form bytes, fields, records and eventually files. You were given an overview of the differences between characterbased and byte-based streams, as well as an introduction to several file-processing classes provided by the java.io package. You used class File to retrieve information about a file or directory. Next, you learned how to use sequential-access file processing to manipulate records that are stored in order by the record-key field. In that discussion, you learned the differences between text-file processing and object serialization, and used serialization to store and retrieve entire objects. You then learned how to use random-access files to instantly retrieve and manipulate fixed-length records. The chapter concluded with an overview of other classes provided by the java.io package, and a small example of using a JFileChooser dialog to allow users to easily select files from a GUI. In the next chapter, you will learn the concept of recursionmethods that call themselves. Defining methods in this manner sometimes leads to more intuitive programs.
[Page 733 (continued)]
Summary
Data stored in variables and arrays is temporarythe data is lost when a local variable goes out of
scope or when the program terminates. Computers use files for long-term retention of large amounts of data, even after the programs that created the data terminate.
Persistent data maintained in files exists beyond the duration of program execution.
Computers store files on secondary storage devices such as hard disks.
The smallest data item in a computer can assume the value 0 or the value 1 and is called a bit. Ultimately, a computer processes all data items as combinations of zeros and ones.
The computer's character set is the set of all characters used to write programs and represent data.
Characters in Java are Unicode characters composed of two bytes, each composed of eight bits.
Just as characters are composed of bits, fields are composed of characters or bytes. A field is a group of characters or bytes that conveys meaning.
Data items processed by computers form a data hierarchy that becomes larger and more complex in structure as we progress from bits to characters to fields, and so on.
Typically, several fields compose a record (implemented as a class in Java).
A record is a group of related fields.
A file is a group of related records.
To facilitate the retrieval of specific records from a file, at least one field in each record is chosen
as a record key. A record key identifies a record as belonging to a particular person or entity and is unique to each record.
There are many ways to organize records in a file. The most common is called a sequential file, in which records are stored in order by the record-key field.
A group of related files is often called a database. A collection of programs designed to create and manage databases is called a database management system (DBMS).
Java views each file as a sequential stream of bytes.
Every operating system provides a mechanism to determine the end of a file, such as an end-of-
file marker or a count of the total bytes in the file that is recorded in a system-maintained administrative data structure.
[Page 734]
Byte-based streams represent data in binary format.
Character-based streams represent data as sequences of characters.
Files that are created using byte-based streams are binary files. Files created using characterbased streams are text files. Text files can be read by text editors, whereas binary files are read
by a program that converts the data to a human-readable format.
Java also can associate streams with different devices. Three stream objects are associated with devices when a Java program begins executingSystem.in, System.out and System.err.
The java.io package includes definitions for stream classes, such as FileInputStream (for byte-
based input from a file), FileOutputStream (for byte-based output to a file), FileReader (for character-based input from a file) and FileWriter (for character-based output to a file). Files are opened by creating objects of these stream classes.
Class File is used to obtain information about files and directories.
Character-based input and output can be performed with classes Scanner and Formatter.
Class Formatter enables formatted data to be output to the screen or to a file in a manner similar to System.out.printf.
A file or directory's path specifies its location on disk.
An absolute path contains all the directories, starting with the root directory, that lead to a
specific file or directory. Every file or directory on a disk drive has the same root directory in its path.
A relative path normally starts from the directory in which the application began executing.
A separator character is used to separate directories and files in the path.
Java imposes no structure on a filenotions such as a record do not exist as part of the Java language. The programmer must structure files to meet an application's requirements.
To retrieve data sequentially from a file, programs normally start reading from the beginning of the file and read all the data consecutively until the desired information is found.
Data in many sequential files cannot be modified without the risk of destroying other data in the
file. Therefore, records in a sequential-access file are not usually updated in place. Instead, the entire file is usually rewritten.
Java provides a mechanism called object serialization that enables entire objects to be written to or read from a stream.
A serialized object is an object represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserializedthat is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
Classes ObjectInputStream and ObjectOutputStream, which respectively implement the
ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream (possibly a file).
Only classes that implement interface Serializable can be serialized and deserialized with
ObjectOutputStreams and ObjectInputStreams.
The ObjectOutput interface contains method writeObject, which takes an Object that implements interface Serializable as an argument and writes its information to an
OutputStream.
The ObjectInput interface contains method readObject, which reads and returns a reference to
an Object from an InputStream. After an object has been read, its reference can be cast to the object's actual type.
[Page 735]
Instant record access is possible with random-access files and with databases. A program can
access individual records of a random-access file directly (and quickly) without searching through other records. Random-access files are sometimes called direct-access files.
Several techniques can be used to create random-access files. Perhaps the simplest is to require that all the records in a file be of the same fixed length.
Using fixed-length records makes it easy for a program to calculate (as a function of the record size and the record key) the exact location of any record relative to the beginning of the file.
When a program associates an object of class RandomAccessFile with a file, the program reads
or writes data, beginning at the location in the file specified by the file-position pointer, and manipulates all the data as primitive types.
RandomAccessFile method seek positions to the exact location in the file at which a record of
information is stored. Method seek sets the file-position pointer to a specific location in the file relative to the beginning of the file.
Buffering is an I/O-performance-enhancement technique. With a BufferedOutputStream, each
output statement does not necessarily result in an actual physical transfer of data to the output device. Rather, each output operation is directed to a region in memory called a buffer that is large enough to hold the data of many output operations. Actual transfer to the output device is then performed in one large physical output operation each time the buffer fills.
With a BufferedInputStream, many "logical" chunks of data from a file are read as one large
physical input operation into a memory buffer. As a program requests each new chunk of data, it is taken from the buffer. When the buffer is empty, the next actual physical input operation from the input device is performed to read in the next group of "logical" chunks of data.
Class JFileChooser is used to display a dialog that enables users of a program to easily select files from a GUI.
[Page 735 (continued)]
Terminology
absolute path
ASCII (American Standard Code for Information Interchange) character set batch file
binary file
bit (binary digit) buffer
byte-based stream byte data type
CANCEL_OPTION constant of class JFileChooser canRead method of class File
canWrite method of class File capacity
character-based stream character set
-classpath command line argument to java -classpath command line argument to javac
data hierarchy database
database management system (DBMS)
DataInput interface
DataInputStream class
DataOutput interface
DataOutputStream class
decimal digit
deserialized object
direct-access application
direct-access files
DIRECTORIES_ONLY constant of class JFileChooser
directory
directory name
disk
end-of-file marker
EndOfFileException
exists method of class File exit method of class System
field
file
File class file-open mode file-position pointer file processing
FileInputStream class
[Page 736]
FileOutputStream class
FileReader class
FILES_AND_DIRECTORIES constant of class JFileChooser FILES_ONLY constant of class JFileChooser
FileWriter class fixed-length record
Formatter class
getAbsolutePath method of class File getName method of class File getParent method of class File getPath method of class File
getSelectedFile method of class JFileChooser
InputStream class instant-access application
IOException
isAbsolute method of class File isDirectory method of class File isFile method of class File java.io package
JFileChooser class
JFileChooser dialog
lastModified method of class File length method of class File
list method of class File logical input operations logical output operations memory buffer
NoSuchElementException
object serialization
ObjectInputStream class
ObjectOutputStream class
optical disk
OutputStream class
parent directory
pathSeparator static field of class File
persistent data
physical input operation
physical output operation
PrintStream class
PrintWriter class
"r" RandomAccessFile open mode random-access file
RandomAccessFile class read-only file
readDouble method of class RandomAccessFile Reader class
readInt method of class RandomAccessFile readLine method of class BufferedReader readObject method of class ObjectInputStream readObject method of interface ObjectInput
record
record key
record size
relative path
root directory
"rw" RandomAccessFile open mode secondary storage devices
seek method of class RandomAccessFile sequential-access file
Serializable interface serialized object
setErr method of class System setIn method of class System setOut method of class System space/time trade-off
setSelectionMode of class JFileChooser
shell script
showOpenDialog of class JFileChooser standard error stream object
stream object stream of bytes
stream processing
System.err (standard error stream) tagging interface
text file
transaction-processing program
TRansient keyword truncated
Unicode character set
URI (Uniform Resource Identifier) wrapped byte array
wrapping of stream objects
writeBoolean method of interface DataOutput writeByte method of interface DataOutput writeBytes method of interface DataOutput writeChar method of interface DataOutput writeChars method of class RandomAccessFile writeChars method of interface DataOutput writeDouble method of class RandomAccessFile writeDouble method of interface DataOutput writeFloat method of interface DataOutput writeInt method of class RandomAccessFile writeInt method of interface DataOutput writeLong method of interface DataOutput writeObject method of class ObjectOutputStream writeObject method of interface ObjectOutput Writer class
writeShort method of interface DataOutput writeUTF method of interface DataOutput
