Download presentation
Presentation is loading. Please wait.
1
Chapter 8: Input and Output
Java Programming - Advanced Topics
2
Objectives In this chapter you will:
Perform stream input/ output (I/O) with the core classes in the package java.io Use the standard streams System.in, System.out, and System.err Distinguish between byte-oriented and character-oriented streams
3
Objectives In this chapter you will:
Write code that uses objects of the File class to navigate a file system Select valid constructor arguments for FilterInputStream and FilterOutputStream subclasses from a list of classes in the java.io package
4
Objectives In this chapter you will:
Write appropriate code to read, write, and update files using FileInputStream, FileOutputStream, and RandomAccessFile objects Describe the permanent effects on the file system of constructing and using FileInputStream, FileOutputStream, and RandomAccessFile objects Use object serialization
5
Programming I/ O Most I/O in the Java platform operates through streams In stream I/O, characters or bytes are read or written sequentially When a file is opened as a stream, all input or output starts at the beginning of the file and proceeds character by character or byte by byte to the end of the file The core classes do not offer much formatting control for the output streams
6
Programming I/ O The package java.text gathers many of the classes and interfaces for handling local customs You can use the core class DecimalFormat in the package java.text to set patterns for formatting and parsing numbers Not all I/O in the Java platform is stream I/O The package java.io includes the core class RandomAccessFile, which you can use to read and write arbitrary locations within a file without first having to read or write all the bytes or characters that precede that location
7
Byte-Oriented Stream Classes
The hierarchies of the byte-oriented stream classes have a superclass for output and another superclass for input All the classes in these hierarchies extend the input and output superclass directly or indirectly, and ultimately extend Object The classes java.io.InputStream and java.io.OutputStream are the roots of a dual hierarchy that encapsulates most of byte-oriented I/O
8
Byte-Oriented Stream Classes
9
Predefined Stream Objects
All Java programs can use three stream objects that are defined in the System class of the java.lang package These objects are System.in, System.out, and System.err Class - java.lang.System Purpose - The System class provides the standard stream objects
10
Predefined Stream Objects
Fields System.in - The field System.in is a java.io.BufferedInputStream object System.out - The field System.out is a java.io.PrintStream object System.err - The field System.err is a java.io.PrintStream object print and printIn, which are sets of overloaded methods of the PrintStream class, are particularly useful for console output
11
Predefined Stream Objects
The printin method appends a line separate to its argument to produce a complete line of output The print method does not add the line separate, so you can build up one line of output with several calls of print The methods print and printIn are overloaded to create versions specifically for the primitive types, for char[ ], and for String
12
Input and Output Methods
You perform most byte-oriented I/O operations by calling methods that are defined in the InputStream and OutputStream classes The subclasses of InputStream and OutputStream add value by overriding and overloading these methods for specific circumstances Methods boolean markSupported() - int available() void mark( int readlimit ) - void close() int read() - void reset() long skip(long bytecount )
13
Input and Output Methods
Class - java.io.OutputStream Purpose - The OutputStream class is the superclass of all byte-oriented output streams Constructors - The constructor of this class, OutPutStream(), takes no arguments Methods void close() - void flush() void write (int b ) - void write (byte[ ] bytebuffer ) void write ( byte[ ] bytebuffer, int offset, int count )
14
Filter Streams A number of classes provide extra functionality in the sense that they add or override methods to preprocess output before actually writing the data, or post-process input after the data has been read These are called filter streams A set of classes that extend FilterInputStream or FilterOutputStream provides them
15
Filter Streams The class FilterInputStream extends InputStream, and the class FilterOutputStream extends OutputStream These abstract classes are designed to act as wrappers for the InputStream and Outputstream classes To use a filter stream, you must already have an InputStream or an OutputStream object
16
Byte-Oriented Filter Streams
17
Other Byte I/O Classes The java.io package defines many classes
Extensions of InputStream include the following: The class ByteArrayInputStream lets you read an array of bytes as though it is an InputStream object The class SequenceInputStream provides a mechanism for concatenating the data from two or more InputStream objects into a single, seamless stream The class PipedInputStream implements half of a pipe and is especially useful for communication between threads
18
Other Byte I/ O Classes Extensions of OutputStream include the following: The class ByteArrayOutputStream sends its output into an object of type byte[ ]. You can use this class to perform your own buffering, or to build an object that another piece of code reads as a ByteArrayInputStream The class PipedOutputStream is the complementary class to PipedInputStream. Together, these two classes comprise a pipe that you can use for communication between threads
19
File I/O Basics Programming stream I/O to and from files is much like programming stream I/O to and from the console Major differences exist between files and the standard console I/O objects System.in, System.out, and System.err: Before you can use a file, you must associate the file with a FileInputStream or FileOutputStream object If you want to access the data in a file in random-access order, you must open it as a RandomAccessFile, not as a FileInputStream In a network environment, the default security restrictions do not let applets do any file I/O on the client workstation
20
File I/O Basics When you perform stream I/O on a file, you are actually manipulating either a FileInputStream object or a FileOutputStream object You must set up the association between the object and the actual file in either of two ways: You can pass the name of the files, as a String, to the constructor of the FileInputStream or FileOutputStream class You can create a File object, passing the name of the file to the constructor of the file class. Then, create the stream object and pass the File object as a parameter of the constructor
21
File I/O Basics Creating a File object has advantages:
When you create the File object, you can perform checks, such as whether an input file exists and is read-only or has read-write capabilities The File class provides a level of insulation from platform-dependent conventions such as whether a separator between subfolder names is a forward slash, /, or backslash, \ Using a FileInputStream object makes no physical change to any data stored on disk However, creating a FileOutputStream object or writing to a RandomAccessFile object does modify physical storage
22
File Navigation Methods
The File class gives you more than a way of checking the status of a file before you perform I/O on it The File class does double duty as a representative of both kinds of file system objects Syntax - java.io.File Purpose - The File class encapsulates most of the platform-dependent complexities of files and path names in a portable manner
23
File Navigation Methods
Constructors File( String filename ) File( File folder, String filename ) File ( String folder, String filename ) Methods boolean canRead() boolean canWrite() File createTempFile( String prefix, String suffix ) File createTempFile( String prefix, String suffix, File folder )
24
File Navigation Methods
boolean delete() void deleteOnExit() boolean exists() String getAbsolutePath() String getName() String getParent() File getParentFile() boolean isDirectory() boolean isFile()
25
File Navigation Methods
long lastModified() String [ ] list() String [ ] list(FilenameFilter filter ) File [ ] listFiles() File [ ] listFiles(fileFilter filter ) File [ ] listFiles(FilenameFilter filter ) File[ ] listRoots() boolean mkdir() boolean setReadOnly() URL toURL()
26
Random-Access File I/O
The class RandomAccessFile supports byte-oriented I/O to and from random-access files Use it to read and write data from or to any specified location within a file RandomAccessFile objects are not streams RandomAccessFile combines input and output operations in one class
27
Character Streams The java.io package has classes that are specifically designed to support character streams The character streams differ from the byte streams mainly in that they operate on the buffered input and output and properly convert each character from the encoding scheme of the native operating system to the Unicode character set used by the Java platform In contrast, InputStream and OutputStream, and the classes that extend them, operate on bytes and arrays of bytes
28
Character Streams The byte-oriented streams correctly handle only seven-bit ASCII characters, which have the same value as the first 128 Unicode characters The hierarchy of classes that support character streams mirrors the structure of the hierarchy of classes that support byte-oriented streams The superclass of character-oriented input stream I/O is java.io.Reader The corresponding output stream is java.io.Writer
29
Character Stream Classes
30
Connecting Byte and Character I/O Classes
The Java platform includes adapter classes that bridge between character I/O classes and the byte I/O classes The InputStreamReader and OutputStreamWriter classes perform the adaptation You cannot create a stream object from a Writer object or a Reader object
31
Using Other Character I/O Classes
Extensions of the Reader object include the following: The class CharArrayReader lets you read an array of characters as though it were a Reader object The class StringReader lets you read a String as though it were a Reader object The class PipeReader implements half of a pipe and is especially useful for communication between threads
32
Using Other Character I/O Classes
Extensions of the Writer object include the following: The class CharArrayWriter sends its output into an object of type char[ ] The class StringWriter lets you write to a StringBuffer as though it were a Writer object The class PipedWriter is the complementary class to PipedReader The class PrintWriter is the character I/O equivalent of the PrintStream class
33
Reading One Token at a Time
The class StreamTokenizer is a utility class in java.io that is not related to any of the other classes by inheritance It lets you read a file as a sequence of tokens by encapsulating a Reader object and grouping the stream of input bytes into tokens By default, tokens are delimited by whitespace, but you can call many methods to customize a tokenizing algorithm
34
Reading One Token at a Time
Whitespace is any combination of space, new line, or tab characters To use the StreamTokenizer class, first create a Reader object, and then pass the Reader object as a parameter to the constructor of the StreamTokenizer object
35
Object Serialization Serializing an object to do the following:
Transmit objects over a network Save objects to files between runs of your program, or perhaps write and then read objects later in the same application For the primitive types, the byte-oriented filter classes DataOutputStream and DataInputStream provide methods to write and read binary representations of variables of all the primitive types o String objects to and from a file
36
Object Serialization Object serialization is a general solution that lets you write objects to I/O streams and then read them, without defining any additional methods Object serialization properly handles not only the fields defined in the class, but also inherited fields and any subfields that these fields may have The object serialization feature is an important component of the Java Remote Method Invocation (RMI) enterprise API
37
Serializing Objects Not all classes of objects support serialization
By default, classes are not serializable To let instance of a class be serialized, define the class with implements Serializable The Serializable interface, like Cloneable, is a marker interface and contains no methods Most of the classes in the java.lang package implement the Serializable interface
38
Serializing Objects Commonly used classes in the java.lang package that do not implement Serializable are Math, Process, Runtime, SecurityManager, System, Thread, ThreadGroup, and Void These omissions make sense for the following reasons: Math and System contain only methods and variables Void is just a placeholder and is essentially empty The nature of the other classes is incompatible with the rationale for object serialization. The Process, Runtime, SecuityManage, Thread, and ThreadGroup objects are used as a program runs
39
Using Object Streams Two stream classes support object serialization:
ObjectOutputStream is a subclass of OutputStream. To create an ObjectOutputStream, provide an existing OutputStream object as the argument of the constructor ObjectInputStream is a subclass of InputStream. To create an ObjectInputStream, provide an existing InputStream object as the argument of the constructor
40
Suppressing Serialization of Fields
Java does not require that every field in a class be serialized Others may be references to objects of classes that do not implement Serializable You can include the qualifier transient when you declare fields to indicate that they should not be serialized with instances of the class When the object is deserialized later, transient fields are given the default value normally used for fields of their type
41
Suppressing Serialization of Fields
You can use the transient qualifier to indicate that certain fields of a class should never be serialized, but it is not very flexible Java provides an alternate approach for runtime control: You can add a private static final field with the name serialPersistentFields and type ObjectStreamField[ ] to the class Programmers are sure to want some ability to customize serialization for a particular class
42
Suppressing Serialization of Fields
Designers have given you two additional methods for this purpose: The readObject and writeObject methods are not part of any interface to be implemented or class to be extended Even though the serialization support calls readObject and writeObject, they must be private methods You must define readObject and writeObject as in the following lines, taken from example program Make sure to call the defaultReadObject and defaultWriteObject methods in customized methods and they do the actual serialization work
43
Specifying the Version Number
You do not make up a version number The value is calculated using a formula that takes the name of the class and its interfaces, fields, and methods You can determine the value with the serialver tool supplied with the SDK, by entering the following command: serialver class_name You can use cut and paste techniques to edit this number into your class definition Alternatively, you may prefer not to define a serialVersionUID field and let the JVM generate one
44
Compatibility of Serialization Formats
The object serialization classes of the Java 2 platform write objects to object streams using a different format from earlier version of the Java platform To identify the serialization stream format used, Java 2 defines two new constants, PROTOCOL_VERSION_1 and PROTOCOL_VERSION_2, in the java.io.ObjectStreamConstants interface
45
Chapter Summary Most input to and output from the JVM is stream-based, regardless of whether your program is communicating with the console, files, or another program running on your network Support for I/O is provided by the core classes in the package java.io For byte-oriented I/O, the two classes InputStream and OutputStream are the abstract classes that are the roots of input and output class hierarchies, respectively
46
Chapter Summary The predefined console input stream object, and System.in, and the console output stream objects, System.out and System.err, are InputStream and OutputStream objects The stream I/O model means that console I/O and file I/O are very similar FileInputStream and FileOutputStream are the classes used for reading and writing files File objects are constructed by providing a string containing a filename in a platform-independent manner
47
Chapter Summary Filter stream classes are designed to wrap either an InputStream or an OutputStream class Several other classes extend the InputStream and OutputStream classes to provide capabilities such as reading and writing byte arrays, sequencing multiple streams as a single stream, and reading and writing pipes Use the class RandomAccessFile to read and write information at arbitrary locations within a file without first having to read or write information at the preceding locations
48
Chapter Summary To enable programmers to read and write objects as whole, the Java programming language provides Object serialization Only classes that implement the marker interface Serializable can be serialized You can exclude individual fields within a class from the serialization operation by applying the transient qualifier
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.