Chapter 19

27
Chapter 19 Binary I/O

description

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 - PowerPoint PPT Presentation

Transcript of Chapter 19

Page 1: Chapter 19

Chapter 19

Binary I/O

Page 2: Chapter 19

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()

Page 3: Chapter 19

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*

Page 4: Chapter 19

Binary I/O Classes

Page 5: Chapter 19

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?

Page 6: Chapter 19

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

Page 7: Chapter 19

And jumping around

• markSupported() // boolean value indicating whether the stream supports marking

• mark( int readlimit ) //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

Page 8: Chapter 19

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]

Page 9: Chapter 19

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

Page 10: Chapter 19

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 IOExceptions that need to be handled

Page 11: Chapter 19

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

Page 12: Chapter 19

Example of binary I/O

Page 13: Chapter 19

Filters

Page 14: Chapter 19

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

Page 15: Chapter 19

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)

Page 16: Chapter 19

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

Page 17: Chapter 19

How to use filter wrappers (and EOF)

Page 18: Chapter 19
Page 19: Chapter 19

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

Page 20: Chapter 19

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!

Page 21: Chapter 19

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()

Page 22: Chapter 19

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

Page 23: Chapter 19

Implementing a serializable class

• Serializable has no methods!• Declare the class to implment Serializable• Everything else is automated

• Caveat: All classes in the inheritance chain must be serializable because all superclass data must be serialized for the object

Page 24: Chapter 19

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*

Page 25: Chapter 19

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.

Page 26: Chapter 19

Serializing Arrays

• Arrays are serializable if all elements of the array are serializable

Page 27: Chapter 19

RandomAccessFile