270 likes | 397 Views
Chapter 19. Binary I/O. Lab 6. Write a program that will generate and handle ten different exceptions User will select error to generate from a menu Program will perform an appropriate operation to throw the interupt (e.g. 1 / 0) Program will catch and report the exception trhown
E N D
Chapter 19 Binary I/O
Lab 6 • Write a program that will generate and handle ten different exceptions • User will select error to generate from a menu • Program will perform an appropriate operation to throw the interupt (e.g. 1 / 0) • Program will catch and report the exception trhown • Demonstrate using printStackTrace(), getStackTrace(), getMessage(), and toString()
Input and Output in Java • I/O operations can be binary or text • Binary reads and writes the exact values as represented in memory • Text is represented as Unicode characters internally in Java (16-bit values) • Text is translated to whatever format is appropriate for the native file system*
InputStream • read() // reads the next byte as an int, returns -1 if end of stream • read( byte[] b) // reads up to b.length bytes, returns the number of bytes read or -1 if end of stream • Read( byte[] b, int offset, int length) //reads bytes into b starting at b[offset]; reads up to length bytes, returns length or -1 if end of stream. What is length + offset > b.length?
Other useful methods • available() // returns an int estimate of the number of bytes that can be read from stream • Skip( long n ) // skips (discards) n bytes from the input stream, returns number of bytes actually skipped • close() // closes the input stream, which releases any resources held
And jumping around • markSupported() // boolean value indicating whether the stream supports marking • mark( intreadlimit ) //marks the current position in stream (to return to later). Readlimit is the maximum number of bytes that can be read before invalidating the mark. • reset() // resets the stream to the position of the last mark
OutputStream • write( int b ) // writes a byte to the stream (the int is cast to a byte) • write( byte[] b ) // writes all of the bytes in the array to the stream • write( byte[] b, int offset, int length) // writes length bytes to the stream starting with b[offset]
Cleaning up • Flush() // forces any buffered bytes to be written to the stream (the device or physical file) • Close() // closes the stream and releases and resources held • Note that all OutputStream methods are defined as void methods
FileInputStream • Concrete class for reading binary data from a file—from a file-oriented source • Two constructors*—either a File object or a String specifying the path and name of the file • FileNotFoundException thrown if the requested file does not exist • I/O operations are a great source of IOExceptionsthat need to be handled
FileOutputStream • Concrete class for writing binary data to a file or file-oriented device • Two constructors—either a File object or a String specifying the path and name of the file • Optional constructor parameter—boolean append flag controlling whether we add to or overwrite an existing file • Non-existent files will be created, if possible
Filters allow structured I/O • FilterInputStream and FilterOutputStream inherit the basic byte-oriented methods • Derived classes must provide wrapper methods to process other data types • DataInputStream and DataOutputStream are classes built in to Java for handling the primitive data types and strings • You can write your own specialty filter classes
DataInputStream & DataOutputStream • Each class contains symmetric methods to read and write primitive data types (boolean, byte, char, float, double, short, integer, long) • Each class also contains methods to read and write lines of text and UTF strings • Data must be written and read in the same order and format (e.g. UTF-8)
The End (of File) • Attempting to read past the end of an InputStream will throw an exception: EOFException • You can use this to determine when to stop reading data, but you may not necessarily want to rely on it • Make sure you close the InputStream no matter what happens
Buffered I/O • Buffered I/O is can be more efficient than direct I/O (faster) • Buffered I/O streams read blocks of data as needed that can be processed in smaller chunks • There is an optimal data block size that depends upon the type of data being processed
Buffered I/O Classes • BufferedInputStream • BufferedOutputStream • These classes inherit the base class methods • The subtype specialization is using a buffer to make reads/writes more efficient • Using buffered I/O is generally a good idea!
Object I/O • The object stream classes implement all of the functionality of the data stream classes plus methods for reading and writing objects • Therefore, object stream classes can replace data stream classes • New methods are added: • readObject() • writeObject()
Serializable • In order for an object to be “readable” or “writeable,” it must implement the serializable interface • Attempting to read/write an object that does not implement Serializable will cause a ClassNotFoundException • This exception must be handled if you read or write objects
Implementing a serializable class • Serializable has no methods! • Declare the class to implmentSerializable • Everything else is automated • Caveat: All classes in the inheritance chain must be serializable because all superclass data must be serialized for the object
The rules of object serialization • Static variables do not get written • All other variables are written unless they are declared with the transient keyword • Each object written is given a serial number to uniquely identify it • Multiple copies of objects are only written once, later copies have only the serial number written*
Object deserialization • Static variables are not stored, therefore they must be saved and set as a separate operation • Normal variables will be restored as expected • Transient variables will not be restored. Their values must be set by some other means. • Multiple copies of the same object will have one copy restored, and all other references will be to that object through serial number.
Serializing Arrays • Arrays are serializable if all elements of the array are serializable