Chapter 17 Files, Streams and Object Serialization Java How to

81 Slides9.84 MB

Chapter 17 Files, Streams and Object Serialization Java How to Program, 8/e 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.2 The java.io Package Java programs perform file processing by using classes from package java.io. Includes definitions for stream classes FileInputStream (for byte-based input from a file) FileOutputStream (for byte-based output to a file) FileReader (for character-based input from a file) FileWriter (for character-based output to a file) You open a file by creating an object of one these stream classes. The object’s constructor opens the file. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.2 The java.io Package(cont.) Can perform input and output of objects or variables of primitive data types without having to worry about the details of converting such values to byte format. To perform such input and output, objects of classes ObjectInputStream and ObjectOutputStream can be used together with the byte-based file stream classes FileInputStream and FileOutputStream. The complete hierarchy of classes in package java.io can be viewed in the online documentation at http://java.sun.com/javase/6 /docs/api/java/io/package-tree.html 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.2 The java.io Package (cont.) Class File provides information about files and directories. Character-based input and output can be performed with classes Scanner and Formatter. Class Scanner is used extensively to input data from the keyboard. This class can also read data from a file. Class Formatter enables formatted data to be output to any text-based stream in a manner similar to method System.out.printf. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.3 Class File Class File provides four constructors. The one with a String argument specifies the name of a file or directory to associate with the File object. The name can contain path information as well as a file or directory name. 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. A relative path normally starts from the directory in which the application began executing and is therefore “relative” to the current directory. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.3 Class File (cont.) The constructor with two String arguments specifies an absolute or relative path and the file or directory to associate with the File object. The constructor with File and String arguments uses an existing File object that specifies the parent directory of the file or directory specified by the String argument. The fourth constructor uses a URI object to locate the file. A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource Locators (URLs) that are used to locate websites. Figure 17.1 lists some common File methods. The http://java.sun.com/javase/6/ docs/api/java/io/File.html 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.3 Class File (cont.) A separator character is used to separate directories and files in the path. On Windows, the separator character is a backslash (\). On Linux/UNIX, it’s a forward slash (/). Java processes both characters identically in a path name. When building Strings that represent path information, use File.separator to obtain the local computer’s proper separator. This constant returns a String consisting of one character— the proper separator for the system. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.4 Case study: A Credit-Inquiry Program To retrieve data sequentially from a file, programs start from the beginning of the file and read all the data consecutively until the desired information is found. It might be necessary to process the file sequentially several times (from the beginning of the file) during the execution of a program. Class Scanner does not allow repositioning to the beginning of the file. The program must close the file and reopen it. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.4 Case study: A Credit-Inquiry Program The data in many sequential files cannot be modified without the risk of destroying other data in the file. If the name “White” needed to be changed to “Worthington,” the old name cannot simply be overwritten, because the new name requires more space. Fields in a text file—and hence records—can vary in size. Records in a sequential-access file are not usually updated in place. Instead, the entire file is usually rewritten. Rewriting the entire file is uneconomical to update just one record, but reasonable if a substantial number of records need to be updated. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5 Object Serialization To read an entire object from or write an entire object to a file, Java provides object serialization. A serialized object is represented as a sequence of bytes that includes the object’s data and its type information. After a serialized object has been written into a file, it can be read from the file and deserialized to recreate the object in memory. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5 Object Serialization (cont.) Classes ObjectInputStream and ObjectOutputStream, which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream. To use serialization with files, initialize ObjectInputStream and ObjectOutputStream objects with FileInputStream and FileOutputStream objects. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5 Object Serialization (cont.) ObjectOutput interface method writeObject takes an Object as an argument and writes its information to an OutputStream. A class that implements ObjectOuput (such as ObjectOutputStream) declares this method and ensures that the object being output implements Serializable. ObjectInput interface method readObject 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. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5.1 Creating a Sequential-Access File Using Object Serialization Objects of classes that implement interface Serializable can be serialized and deserialized with ObjectOutputStreams and ObjectInputStreams. Interface Serializable is a tagging interface. It does not contain methods. A class that implements Serializable is tagged as being a Serializable object. An ObjectOutputStream will not output an object unless it is a Serializable object. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5.1 Creating a Sequential-Access File Using Object Serialization (cont.) In a class that implements Serializable, every variable must be Serializable. Any one that is not must be declared transient so it will be ignored during the serialization process. All primitive-type variables are serializable. For reference-type variables, check the class’s documentation (and possibly its superclasses) to ensure that the type is Serializable. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5.2 Reading and Deserializing Data from a Sequential-Access File The program in Figs. 17.10–17.21 reads records from a file created by the program in Section 17.5.1 and displays the contents. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.5.2 Reading and Deserializing Data from a Sequential-Access File (cont.) ObjectInputStream method readObject reads an Object from a file. Method readObject throws an EOFException if an attempt is made to read beyond the end of the file. Method readObject throws a ClassNotFoundException if the class for the object being read cannot be located. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6 Additional java.io Classes This section overviews additional interfaces and classes (from package java.io) for byte-based input and output streams and character-based input and output streams. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output InputStream and OutputStream are abstract classes that declare methods for performing byte-based input and output, respectively. Pipes are synchronized communication channels between threads. PipedOutputStream (a subclass of OutputStream) and PipedInputStream (a subclass of InputStream) establish pipes between two threads in a program. One thread sends data to another by writing to a PipedOutputStream. The target thread reads information from the pipe via a PipedInputStream. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) A FilterInputStream filters an InputStream, and a FilterOutputStream filters an OutputStream. Filtering means simply that the filter stream provides additional functionality, such as aggregating data bytes into meaningful primitive-type units. FilterInputStream and FilterOutputStream are typically extended, so some of their filtering capabilities are provided by their subclasses. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) A PrintStream (a subclass of FilterOutputStream) performs text output to the specified stream. System.out and System.err are PrintStream objects. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) Usually, programs read data as aggregates of bytes that form ints, floats, doubles and so on. Java programs can use several classes to input and output data in aggregate form. Interface DataInput describes methods for reading primitive types from an input stream. Classes DataInputStream and RandomAccessFile each implement this interface to read sets of bytes and process them as primitive-type values. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) Interface DataOutput describes a set of methods for writing primitive types to an output stream. Classes DataOutputStream (a subclass of FilterOutputStream) and RandomAccessFile each implement this interface to write primitive-type values as bytes. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) Buffering is an I/O-performance-enhancement technique. With a BufferedOutputStream, each output operation is directed to a buffer holds the data of many output operations Transfer to the output device is performed in one large physical output operation each time the buffer fills. The output operations directed to the output buffer in memory are often called logical output operations. A partially filled buffer can be forced out to the device at any time by invoking the stream object’s flush method. Using buffering can greatly increase the performance of an application. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) 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’s taken from the buffer. This procedure is sometimes referred to as a logical input operation. When the buffer is empty, the next actual physical input operation from the input device is performed. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) Java stream I/O includes capabilities for inputting from byte arrays in memory and outputting to byte arrays in memory. A ByteArrayInputStream (a subclass of InputStream) reads from a byte array in memory. A ByteArrayOutputStream (a subclass of OutputStream) outputs to a byte array in memory. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.1 Interfaces and Classes for ByteBased Input and Output (cont.) A SequenceInputStream (a subclass of InputStream) logically concatenates several InputStreams The program sees the group as one continuous InputStream. When the program reaches the end of one input stream, that stream closes, and the next stream in the sequence opens. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.2 Interfaces and Classes for Character-Based Input and Output The Reader and Writer abstract classes are Unicode two-byte, character-based streams. Most of the byte-based streams have corresponding character-based concrete Reader or Writer classes. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.2 Interfaces and Classes for Character-Based Input and Output (cont.) Classes BufferedReader (a subclass of abstract class Reader) and BufferedWriter (a subclass of abstract class Writer) enable buffering for character-based streams. Classes CharArrayReader and CharArrayWriter read and write, respectively, a stream of characters to a char array. A LineNumberReader (a subclass of BufferedReader) is a buffered character stream that keeps track of the number of lines read. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.6.2 Interfaces and Classes for Character-Based Input and Output (cont.) An InputStream can be converted to a Reader via class InputStreamReader. An OuputStream can be converted to a Writer via class OutputStreamWriter. Class File-Reader and class FileWriter read characters from and write characters to a file. Class PipedReader and class PipedWriter implement piped-character streams for transfering data between threads. Class StringReader bStringWriter read characters from and write characters to Strings. A PrintWriter writes characters to a stream. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.7 Opening Files with JFileChooser Class JFileChooser displays a dialog that enables the user to easily select files or directories. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

1992-2010 by Pearson Education, Inc. All Rights Reserved.

17.7 Opening Files with JFileChooser (cont.) JFile-Chooser method setFile-SelectionMode specifies what the user can select from the fileChooser. JFileChooser static constant FILES AND DIRECTORIES indicates that files and directories can be selected. Other static constants include FILES ONLY (the default) and DIRECTORIES ONLY. Method showOpenDialog displays a JFileChooser dialog titled Open. A JFileChooser dialog is a modal dialog. Method showOpenDialog returns an integer specifying which button (Open or Cancel) the user clicked to close the dialog. JFileChooser method getSelectedFile returns the selected file as a File object. 1992-2010 by Pearson Education, Inc. All Rights Reserved.

Back to top button