slide3.3_2009 - Module 3.3 Module Binary I/O Binary...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 3.3 Module Binary I/O Binary EE3206/EE5805 Java Programming and Applications 1 Intended Learning Outcomes To discover how I/O is processed in Java. To To distinguish between text I/O and binary I/O. To To read and write binary files using FileInputStream and FileOutputStream. FileInputStream and FileOutputStream To read and write primitive values and strings using DataInputStream and DataOutputStream. DataInputStream and DataOutputStream To speed up reading/writing by using BufferedInputStream and BufferedOutputStream. BufferedInputStream and BufferedOutputStream To store and restore objects using ObjectOutputStream and ObjectInputStream. ObjectOutputStream and ObjectInputStream To understand how objects are serialized and what kind of objects can be serialized. To can To implement the Serializable iinterface to make objects serializable. Serializable nterface serializable To read and write the same file at random location using the RandomAccessFile class. RandomAccessFile EE3206/EE5805 Java Programming and Applications 2 Text File vs. Binary File Data stored in a text file is represented in human-readable form. Data readable Data stored in a binary file is represented in binary form, which iis s Data designed to be read by machine efficiently. designed For example, Java source programs are stored in text format and can be read by a text editor, but Java classes are stored in binary format and are read by the JVM. The advantage of binary files is that they are more efficient to The process than text files. To represent 10 in binary format: 00001010 To represent 10 in text format using Ascii coding: ‘1’ ’0’ 00110001 00110000 EE3206/EE5805 Java Programming and Applications 3 How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the File not methods for reading/writing data from/to a file. In order to perform I/O, you need methods form to create objects using appropriate Java I/O classes. e.g. Scanner Program Input object created from an input class Output object created from an output class Input stream 01011…1001 File e.g. PrintWriter PrintWriter 11001…1011 Output stream File EE3206/EE5805 Java Programming and Applications 4 Binary I/O Classes FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream Abstract Classes • contains an abstract read method and write method EE3206/EE5805 Java Programming and Applications 5 java.io.InputStream +read(): int +read(b: byte): int +read(b: byte, off: int, len: int): int +available(): int +close(): void +skip(n: long): long InputStream/OutputStream InputStream/OutputStream Reads the next byte of data from the input stream. The value byte is returned as an int value in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value –1 is returned. Reads up to b.length bytes into array b from the input stream and returns the actual number of bytes read. Returns -1 at the end of the stream. Reads bytes from the input stream and stores into b[off], b[off+1], …, b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream. Returns the number of bytes that can be read from the input stream. Closes this input stream and releases any system resources associated with the stream. Skips over and discards n bytes of data from this input stream. The actual number of bytes skipped is returned. +markSupported(): boolean Tests if this input stream supports the mark and reset methods. +mark(readlimit: int): void Marks the current position in this input stream. +reset(): void Repositions this stream to the position at the time the mark method was last called on this input stream. java.io.OutputStream +write(int b): void +write(b: byte): void +write(b: byte, off: int, len: int): void +close(): void +flush(): void the byte value is read/written as an int type the int Writes the specified byte to this output stream. The parameter b is an int value. (byte)b is written to the output stream. Writes all the bytes in array b to the output stream. Writes b[off], b[off+1], …, b[off+len-1] into the output stream. Closes this input stream and releases any system resources associated with the stream. Flushes this output stream and forces any buffered output bytes to be written out. EE3206/EE5805 Java Programming and Applications 6 FileInputStream/FileOutputStream FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream FileInputStream/FileOutputStream FileInputStream/FileOutputStream Associates a binary input/output stream with an external file. All the methods are inherited from their superclasses. superclasses Are meant for reading/writing streams of raw bytes such as image data. For raw such reading/writing streams of characters, consider using FileReader/FileWriter. FileReader/FileWriter EE3206/EE5805 Java Programming and Applications 7 FileInputStream/FileOutputStream To construct a FileInputStream, use the following constructors: FileInputStream public FileInputStream(String filename) FileInputStream(String public FileInputStream(File file) FileInputStream(File A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream java.io.FileNotFoundException would FileInputStream with a nonexistent file. with To construct a FileOutputStream, use the following constructors: FileOutputStream public FileOutputStream(String filename) FileOutputStream(String public FileOutputStream(File file) FileOutputStream(File public FileOutputStream(String filename, boolean append) FileOutputStream(String filename, boolean public FileOutputStream(File file, boolean append) FileOutputStream(File file, boolean If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and constructors etain append new data into the file, use the last two constructors by passing true to the append parameter. parameter. TestFileStream EE3206/EE5805 Java Programming and Applications Run 8 DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts reads them into appropriate primitive type values or strings. FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream DataOutputStream converts primitive type values or strings DataOutputStream converts into bytes and output the bytes to the stream. into EE3206/EE5805 Java Programming and Applications 9 DataInputStream DataInputStream iis a subclass of InputStream and implements the DataInput DataInputStream s InputStream and DataInput interface. InputStream java.io.DataInput +readBoolean(): boolean Reads a Boolean from the input stream. +readByte(): byte Reads a byte from the input stream. +readChar(): char +readFloat(): float +readDouble(): float DataInputStream +DataInputStream( in: InputStream) +readInt(): int +readLong(): long +readShort(): short +readLine(): String +readUTF(): String Reads a character from the input stream. Reads a float from the input stream. Reads a double from the input stream. Reads an int from the input stream. Reads a long from the input stream. Reads a short from the input stream. Reads a line of characters from input. Reads a string in UTF format. 10 FilterInputStream EE3206/EE5805 Java Programming and Applications DataOutputStream DataOutputStream iis a subclass of OutputStream and implements the DataOutputStream s OutputStream and DataOutput interface. DataOutput OutputStream java.io.DataOutput +writeBoolean(b: Boolean): void Writes a Boolean to the output stream. +writeByte(v: int): void Writes to the output stream the eight low-order bits of the argument v. +writeBytes(s: String): void Writes the lower byte of the characters in a string to the output stream. +writeChar(c: char): void Writes a character (composed of two bytes) to the output stream. +writeChars(s: String): void Writes every character in the string s, to the output stream, in order, two bytes per character. +writeFloat(v: float): void Writes a float value to the output stream. +writeDouble(v: float): void +writeInt(v: int): void +writeLong(v: long): void +writeShort(v: short): void +writeUTF(s: String): void Writes a double value to the output stream. Writes an int value to the output stream. Writes a long value to the output stream. Writes a short value to the output stream. Writes two bytes of length information to the output stream, followed by the UTF representation of every character in the string s. 11 FilterOutputStream DataOutputStream +DataOutputStream( out: OutputStream) EE3206/EE5805 Java Programming and Applications Why UTF-8? What is UTF-8? UTF (Unicode Transformation Format) UTF UTF-8 iis a coding scheme that allows systems to operate with UTF s both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of ASCII. the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII bit character as a 16-bit Unicode character. character bit The UTF-8 iis an alternative scheme that stores a character using s The 1,, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one 1 byte. Unicode values less than 0x7FF are coded in two bytes. byte. Other Unicode values are coded in three bytes. 0000 to 007F 0080 to 07FF 0800 to FFFF -> -> -> 1-byte codeword (hh) 2-byte codeword (hhhh) 3-byte codeword (hhhhhh) 12 EE3206/EE5805 Java Programming and Applications Using DataInputStream/DataOutputStream Using DataInputStream/DataOutputStream The two data I/O stream classes work like a filter. When they are constructed, an The constructed, InputStream or OutputStream object is supplied. The data streams then read/write InputStream or OutputStream object from the supplied streams and perform filtering on the data (e.g. converting multiple from converting bytes to certain primitive values). They are created using the following constructors: bytes public DataInputStream(InputStream instream) public DataInputStream(InputStream public DataOutputStream(OutputStream outstream) public DataOutputStream(OutputStream The statements given below create data streams. The first statement creates an input The ent stream for file in.dat; the second statement creates an output stream for file out.dat. in.dat the out.dat DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); new DataInputStream(new DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); new DataOutputStream(new TestDataStream EE3206/EE5805 Java Programming and Applications Run 13 BufferedInputStream/BufferedOutputStream FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream BufferedInputStream/BufferedOutputStream does not contain new methods BufferedInputStream does but uses buffers to speed up I/O operations. speed All the methods BufferedInputStream/BufferedOutputStream are inherited BufferedInputStream are from the InputStream/OutputStream classes. InputStream EE3206/EE5805 Java Programming and Applications 14 Constructing Constructing BufferedInputStream/BufferedOutputStream BufferedInputStream/BufferedOutputStream // Create a BufferedInputStream // BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream public BufferedInputStream(InputStream iin, int bufferSize) public BufferedInputStream(InputStream n, int // Create a BufferedOutputStream // BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStream public BufferedOutputStream(OutputStreamr out, int bufferSize) public BufferedOutputStream(OutputStreamr out, int An internal buffer (byte array) of length bufferSize is created. EE3206/EE5805 Java Programming and Applications 15 Case Studies: Copy File Case This case study develops a program that copies files. The user needs to This eeds provide a source file and a target file as command-lline arguments using ine provide the following command: the java Copy source target The program copies a source file to a target file and displays the The he number of bytes in the file. If the source does not exist, tell the user the file is not found. If the target file already exists, tell the user the file file ser already exists. Copy Run EE3206/EE5805 Java Programming and Applications 16 Object I/O DataInputStream/DataOutputStream enables you to perform I/O for primitive DataInputStream enables type values and strings. type values ObjectInputStream/ObjectOutputStream enables you to perform I/O for ObjectInputStream enables objects iin addition for primitive type values and strings. objects n FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream EE3206/EE5805 Java Programming and Applications 17 ObjectInputStream/ObjectOutputStream Object I/O stream classes implement ObjectInput or ObjectOutput ObjectInput or ObjectOutput iinterfaces that are subclasses of DataInput and DataOutput iinterfaces. nterfaces DataInput and DataOutput nterfaces. java.io.InputStream java.io.DataInput java.io.ObjectInput +readObject(): Object Reads an object. java.io.ObjectInputStream +ObjectInputStream(in: InputStream) java.io.OutputStream java.io.DataOutput java.io.ObjectOutput +writeObject(o: Object): void Writes an object. 18 java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream) EE3206/EE5805 Java Programming and Applications Using Object Streams You may wrap an ObjectInputStream/ObjectOutputStream on any ObjectInputStream/ObjectOutputStream on InputStream/OutputStream using the following constructors: InputStream/OutputStream // Create an ObjectInputStream // ObjectInputStream public ObjectInputStream(InputStream in) public ObjectInputStream(InputStream // Create an ObjectOutputStream // ObjectOutputStream public ObjectOutputStream(OutputStream out) public ObjectOutputStream(OutputStream out) TestObjectOutputStream TestObjectInputStream EE3206/EE5805 Java Programming and Applications Run Run 19 The Serializable Interface The Serializable Not all objects can be written to an output stream. Objects that Not can be written to an object stream is said to be serializable. A can serializable serializable object is an instance of the java.io.Serializable iinterface. serializable object java.io.Serializable nterface. So the class of a serializable object must implement Serializable. serializable object Serializable The Serializable iinterface is a marker interface. It has no methods, Serializable nterface marker It so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Serializable Implementing Java serialization mechanism to automate the process of storing the objects and arrays. EE3206/EE5805 Java Programming and Applications 20 The transient Keyword The transient If an object is an instance of Serializable, but it contains non-serializable iinstance nstance Serializable data fields, can the object be serialized? The answer is no. To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM transient keyword to ignore these fields when writing the object to an object stream. to am. Consider the following class: Consider public class Foo implements java.io.Serializable { public Foo implements java.io.Serializable private int v1; int private static double v2; private static private transient A v3 = new A(); private transient v3 } class A { } // A is not serializable class serializable When an object of the Foo class is serialized, only variable v1 is serialized. Variable Foo class v2 is not serialized because it is a static variable, and variable v3 is not serialized static and because it is marked transient. If v3 were not marked transient, a transient If java.io.NotSerializableException would occur. java.io.NotSerializableException EE3206/EE5805 Java Programming and Applications 21 Serializing Arrays Serializing An array is serializable iif all its elements are serializable. So an entire serializable f serializable So array can be saved using writeObject iinto a file and later restored using writeObject nto readObject. This example stores an array of five int values an array of readObject This int values three strings, and an array of two JButton objects, and reads them back JButton objects, to display on the console. to TestObjectStreamForArray Run EE3206/EE5805 Java Programming and Applications 22 Random Access Files All of the streams you have used so far are known as read-only or read or write-only streams. write streams. The external files of these streams are sequential files that cannot be The nnot updated without creating a new file. That means you may append new updated ew data but cannot change existing data. It is often necessary to modify files or to insert new records into It nto files. Java provides the RandomAccessFile class to allow a file to be RandomAccessFile class read from and write to at random locations. random Many methods in RandomAccessFile are the same as those in RandomAccessFile are DataInputStream and DataOutputStream. For example, DataInputStream and DataOutputStream For readInt(), readLong(), writeDouble(), readLine(), readInt readLong writeDouble readLine writeInt(), and writeLong() can be used in data input stream writeInt and writeLong can or data output stream as well as in RandomAccessFile streams. RandomAccessFile EE3206/EE5805 Java Programming and Applications 23 RandomAccessFile DataInput DataOutput java.io.RandomAccessFile +RandomAccessFile(file: File, mode: String) +RandomAccessFile(name: String, mode: String) +close(): void +getFilePointer(): long +length(): long +read(): int +read(b: byte): int +read(b: byte, off: int, len: int) : int +seek(long pos): void +setLength(newLength: long): void +skipBytes(int n): int +write(b: byte): void +write(byte b, int off, int len) Creates a RandomAccessFile stream with the specified File object and mode. Creates a RandomAccessFile stream with the specified file name string and mode. Closes the stream and releases the resource associated with the stream. Returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. Returns the length of this file. Reads a byte of data from this file and returns –1 an the end of stream. Reads up to b.length bytes of data from this file into an array of bytes. Reads up to len bytes of data from this file into an array of bytes. Sets the offset (in bytes specified in pos) from the beginning of the stream to where the next read or write occurs. Sets a new length of this file. Skips over n bytes of input discarding the skipped bytes. Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. Writes len bytes from the specified byte array starting at offset off to +write(b: byte, off: int, len: int): this file. void EE3206/EE5805 Java Programming and Applications 24 File Pointer A random access file consists of a sequence of bytes. There is a special random special marker called file pointer that is positioned at one of these bytes. A read file that or write operation takes place at the location of the file pointer. When a or er. file is opened, the file pointer sets at the beginning of the fille. When you e. file read or write data to the file, the file pointer moves forward to the next read the data. For example, if you read an int value using readInt(), the JVM reads int value readInt the four bytes from the file pointer and now the file pointer is four bytes four from ahead of the previous location. ahead file pointer file byte byte … byte byte byte byte byte file pointer … byte byte byte byte byte (A) Before readInt() file byte byte … byte byte byte byte byte … byte byte byte byte byte (B) After readInt() 25 EE3206/EE5805 Java Programming and Applications RandomAccessFile Methods void seek(long pos) throws IOException; IOException Sets the file-pointer offset, measured from the beginning pointer of this file, at which the next read or write occurs. of long getFilePointer() IOException; getFilePointer() IOException Returns the current offset, in bytes, from the beginning of Returns the file to where the next read or write occurs. the long length()IOException length()IOException Returns the length of the file. EE3206/EE5805 Java Programming and Applications 26 RandomAccessFile Constructor //allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); new RandomAccessFile("test.dat "); //read only // RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); new RandomAccessFile("test.dat TestRandomAccessFile Run EE3206/EE5805 Java Programming and Applications 27 ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online