Sei sulla pagina 1di 76

Chapter 2 Binary I/O

Streams
Your program can get input from a data source by reading a sequence characters from a stream attached to the source. Your program can produce output by writing a sequence of characters to an output stream attached to a destination. The Java development environment includes a package, java.io, that contains a set of input and output streams that your programs can use to read and write data. The InputStream and OutputStream classes in java.io are the abstract superclasses that define the behaviour for sequential input and output streams in Java. Also included in java.io are several InputStream and OutputStream subclasses that implement specific types of input and output streams.

Streams
If the data flows into your program, the stream is called an input stream. If the data flows out of your program, the stream is called an output stream. For example, if an input stream is connected to the keyboard, the data flows from the keyboard into your program. If an input stream is connected to a file, the data flows from the file into your program. See in the next grapghs

Stream example

Streams

Streams cont
When dealing with input/output, you have to keep in mind that there are two broad categories of data: machine-formatted data and human-readable text. Machine-formatted data is represented in binary form, in which the data is represented inside the computer, as strings of zeros and ones. Human-readable data is in the form of characters. When you read a number such as 3.141592654, you are reading a sequence of characters and interpreting them as a number. The same number would be represented in the computer as a bit-string that you would nd unrecognizable.

Stream cont
To deal with the two broad categories of data representation, Java has two broad categories of streams: byte streams for machine-formatted data and character streams for human readable data. There are many predened classes that represent streams of each type. An object that outputs data to a byte stream belongs to one of the subclasses of the abstract class OutputStream. Objects that read data from a byte stream belong to subclasses of InputStream. If you write numbers to an OutputStream, you wont be able to read the resulting data yourself. But the data can be read back into the computer with an InputStream. The writing and reading of the data will be very ecient, since there is no translation involved: the bits that are used to represent the data inside the computer are simply copied to and from the streams.

Stream cont
Byte streams can be useful for direct machine-tomachine communication, and they can sometimes be useful for storing data in les, especially when large amounts of data need to be stored eciently, such as in large databases. The standard stream classes discussed in this section are dened in the package java.io, along with several supporting classes. You must import the classes from this package if you want to use them in your program.

Stream cont
That means either importing individual classes or putting the directive import java.io.*; at the beginning of your source between the package declaration and class declaration . Streams are necessary for working with les and for doing communication over a network. They can also be used for communication between two concurrently running threads, and there are stream classes for reading and writing data stored in the computer s memory. The beauty of the stream abstraction is that it is as easy to write data to a le or to send data over a network as it is to print information on the screen.

Binary I/O Classes


FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

10

InputStream
Abstract classes The parent class of all byte streams Class declaration
Public abstract class InputStream extends object

public abstract class InputStream extends Object This abstract class is the superclass of all classes representing an input stream of bytes. It defines the methods common to all byte streams

Methods of InputStream
public abstract int available() throws IOException
This method returns the number of bytes that can be read without having to wait for more data to become available, or in other words, blocking. A subclass of InputStream must implement this method.

public void close() throws IOException


This method closes the input stream and releases any resources associated with it. The implementation of the close() method in InputStream does nothing; a subclass should override this method to handle cleanup for the stream.

Methods of IS
public void mark(int readlimit) Parameters
Readlimit :- The maximum number of bytes that can be read before the saved position can become invalid. This method tells this InputStream object to remember its current position, so that the position can be restored by a call to the reset() method. The InputStream can read readlimit bytes beyond the marked position before the mark becomes invalid The method must be overrided in the subclass To use this message use the subclass BuffredINputStream and take the object of FileInputStream/InputStream as a parameter.

public boolean markSupported()


This method returns a boolean value that indicates whether or not this object supports mark-and-reset functionality.

Methods of IS
abstract int read(),int read(byte[] b), public int read(byte[] b, int off, int len), public void reset(), public long skip(long n), are the methods which is found in the IS class.

OutputStream
It is also abstract class Class declaration
public abstract class OutputStream extends Object

This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to the sink or the destination.

Methods of outputStream
public void close() throws IOException
This method closes the output stream and releases any resources associated with it. The implementation of the close() method in OutputStream does nothing; a subclass should override this method to handle cleanup for the stream. This method forces any bytes that may be buffered by the output stream to be written. The implementation of flush() in OutputStream does nothing; a subclass should override this method as needed.

public void flush() throws IOException

public abstract void write(int b) throws IOException

This method writes a byte of output. The method blocks until the byte is actually written. A subclass of OutputStream must implement this method.

Methods of outputStream
public void write(byte[] b) throws IOException
This method writes the bytes from the given array by calling write(b, 0, b.length). The method blocks until the bytes are actually written.

public void write(byte[] b, int off, int len) throws IOException


public void write(byte[] b, int off, int len) throws IOException

FileInputStream/FileOutputStream
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

18

FIS/FOS
FileInputStream / FileOutputStream is for reading/writing bytes from/to files. All the methods in these classes are inherited from InputStream and OutputStream. FileInputStream / FileOutputStream does not introduce new methods.

FileInputStream
To construct a FileInputStream, use the following constructors:

A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file. FileInputStream inputs a stream of bytes from a file
20

FileOutputStream
To construct a FileOutputStream, use the following constructors:

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 append new data into the file, use the last two constructors by passing true to the append parameter. FileOutputStream outputs a stream of bytes to a file.
21

Methods in FIS
NB: all the methods of FIS and FOS are inherited from the superclass IS and OS respectively java.io.FileInputStream.available() method
The java.io.FileInputStream.available() method returns number of remaining bytes that can be read from this input stream without blocking by the next method call for this input stream. The next method call can also be the another thread. Declaration Parameters
NA public int available()

Return Value Exception


The methods returns and estimated of the number of remaining bytes that can be read from this input stream without blocking. IOException -- If the file input stream has been closed by calling close or any I/O error occurs.

Methods in FIS
java.io.FileInputStream.close()
closes this file input stream and releases any system resources associated with the stream.

Declaration
public void close()

Parameters
NA

Return Value
The methods doesnot return any value.

Exception
IOException -- If any I/O error occurs.

Methods in FIS
java.io.FileInputStream.finalize()
This method ensures that the close method of this file input stream is called when there are no more references to it.

Declaration
protected void finalize()

Parameters
NA

Return Value
This method does not return any value.

Exception
IOException -- if an I/O error occurs..

Methods in FIS
java.io.FileInputStream.read() Declaration Parameters
NA This method reads a byte of data from this input stream. The method blocks if no input is available. public int read()

Return Value Exception

The methods returns the next byte of data, or -1 if the end of the file is reached. IOException - If an I/O error occurs

Methods in FIS
java.io.FileInputStream.read(byte[] b, int off, int len) This method reads upto len bytes of data from this input stream into an array of bytes, starting at offset off in the destination array b. Declaration
public int read(byte[] b, int off, int len) b - the byte array into which data is read. off - the start offset in the destination array b. len - the maximum number of bytes to be read.

Parameters

Return Value
The method returns the total number of bytes read into the buffer

Exception
IOException - If an I/O error occurs. NullPointerException - If b is null. IndexOutOfBoundsException - If len or off is negative, or b.length-off is greater than b.length.

Methods in FIS
java.io.FileInputStream.skip(long n) This method skips over and discards n bytes of data from the input stream. Declaration
public long skip(long n)

Parameters

n - the number of bytes to be skipped. The method returns the actual number of bytes skipped. IOException - If an I/O error occurs, if n is negative or if the stream does not support seek.

Return Value Exception

NB-the method we have seen so far is not all the methods of this class and try to read the remaining methods .

Methods of FOS
java.io.FileOutputStream.write(int b)
This method method writes the single byte to this file output stream.

Declaration
public void write(int b)

Parameters
b -- the byte to be written.

Return Value
This method does not return any value.

Exception
IOException - if any I/O error occurs.

Methods of FOS
java.io.FileOutputStream.write(byte[] b)
This method writes b.length bytes from the specified bytearray to this file output stream.

Declaration
public void write(byte[] b)

Parameters
b -- the source buffer.

Return Value
This method does not return any value.

Exception
IOException - if any I/O error occurs.

Methods of FOS
java.io.FileOutputStream.write(byte[] b, int off, int len) Declaration
public void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this file output stream.

Parameters
b -- the source buffer. off -- the start offset in the data. len -- the number of bytes to write.

Return Value
This method does not return any value.

Exception
IOException - if any I/O error occurs.

NB-the method we have seen so far is not all the methods of this class and try to read the remaining methods .

//Example for FileInputStream && OutputStraem import java.io.*; public class TestFileStream { public static void main(String[] args) throws IOException { // Create an output stream to the file FileOutputStream output = new FileOutputStream(test.txt"); for (int i = 1; i <= 10; i++) { output.write(i); } output.close(); FileInputStream input = new FileInputStream (test.txt"); int value; while ((value = input.read()) != -1) { System.out.print(value + " "); } input.close(); } }

Interpretation of the example


A FileOutputStream is created for file test.txt in line 6. The for loop writes ten byte values into the file (lines 7-8). Invoking write(i) is the same as invoking write((byte)i). Line 10 closes the output stream. Line 11 creates a FileInputStream for file text.txt. Values are read from the file and displayed on the console in lines 13 14. The expression ((value = input.read()) != - 1) (line 13) reads a byte from input.read(), assigns it to value, and checks whether it is 1. The input value of 1 signifies the end of a file. The file text.txt created in this example is a binary file. It can be read from a Java program but not from a text editor

FIS/FOS
Almost all the methods in the I/O classes throw java.io.IOException. Therefore you have to declare java.io.IOException to throw in the method or place the code in a try- catch block, as shown below:

DataInputStream/DataOutputStream
DataInputStream reads bytes from the stream and converts 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 into bytes and output the bytes to the stream.
34

DataInputStream
The Java.io.DataInputStream class lets an application read primitive Java data types from an underlying input stream in a machine-independent way. Following are the important points about DataInputStream: Class declaration

An application uses a data output stream to write data that can later be read by a data input stream. public class DataInputStream extends FilterInputStream implements DataInput

Field It contains the following field Constructor & Description

protected InputStream in -- This is the input stream to be filtered. DataInputStream(InputStream in) This creates a DataInputStream that uses the specified underlying InputStream.

Methods of DataInputStream
int read(byte[] b)
This method reads some number of bytes from the contained input stream and stores them into the buffer array b This method reads up to len bytes of data from the contained input stream into an array of bytes. This method reads one input byte and returns true if that byte is nonzero, false if that byte is zero. This method reads and returns one input byte. This method reads two input bytes and returns a char value. This method reads eight input bytes and returns a double value.

int read(byte[] b, int off, int len) boolean readBoolean() byte readByte()

char readChar()

double readDouble()

Methods of DIS
float readFloat()
This method reads four input bytes and returns a float value.

void readFully(byte[] b)
This method reads some bytes from an input stream and stores them into the buffer array b.

void readFully(byte[] b, int off, int len)


This method reads len bytes from an input stream.

int readInt()
This method reads four input bytes and returns an int value.

long readLong()
This method reads eight input bytes and returns a long value.

short readShort()
This method reads two input bytes and returns a short value.

int readUnsignedByte()
This method reads one input byte, zero-extends it to type int, and returns the result, which is therefore in the range 0 through 255.

Methods of DIS cont..


int readUnsignedShort() String readUTF()
This method reads two input bytes and returns an int value in the range 0 through 65535. This method reads in a string that has been encoded using a modified UTF-8 format. This method reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String. This method makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes.

static String readUTF(DataInput in) int skipBytes(int n)

DataOutputStream class
The Java.io.DataOutputStream class lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in. Class declaration
public class DataOutputStream extends FilterOutputStream implements DataOutput

Field

protected int written -- This is the number of bytes written to the data output stream so far. protected OutputStream out -- This is the underlying output stream to be filtered. DataOutputStream(OutputStream out) This creates a new data output stream to write data to the specified underlying output stream.

Class constructors

Methods DOS
void flush()
This method flushes this data output stream.

int size()
This method returns the current value of the counter written, the number of bytes written to this data output stream so far.

void write(byte[] b, int off, int len)


This method writes len bytes from the specified byte array starting at offset off to the underlying output stream.

void write(int b)
This method writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

void writeBoolean(boolean v)
This method writes a boolean to the underlying output stream as a 1-byte value.

void writeByte(int v)
This method writes out a byte to the underlying output stream as a 1-byte value.

Method cont
oid writeBytes(String s) void writeChar(int v)
This method writes out the string to the underlying output stream as a sequence of bytes. This method writes a char to the underlying output stream as a 2-byte value, high byte first.. This method writes a string to the underlying output stream as a sequence of characters. This method converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first. This method converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

void writeChars(String s)

void writeDouble(double v)

void writeFloat(float v)

Methods of DOS con..


void writeInt(int v) This method writes an int to the underlying output stream as four bytes, high byte first. void writeLong(long v) This method writes a long to the underlying output stream as eight bytes, high byte first. void writeShort(int v) void writeUTF(String str)

This method writes a short to the underlying output stream as two bytes, high byte first. This method writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Characters and Strings in Binary I/O


A Unicode consists of two bytes. The writeChar(char c) method writes the Unicode of character c to the output. The writeChars(String s) method writes the Unicode for each character in the string s to the output.
Why UTF-8? What is UTF-8? UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicode character set. Since most applications need only the ASCII character set, it is a waste to represent an 8-bit ASCII character as a 16-bit Unicode character.
The UTF-8 is an alternative scheme that stores a character using 1, 2, or 3 bytes. ASCII values (less than 0x7F) are coded in one byte. Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.

43

Exmple
import java.io.*; public class DataINputAndOUTputDemao { public static void main(String[] args) throws IOException{ InputStream is=null; OutputStream os=null; DataInputStream dis=null; DataOutputStream dos=null; String[]s={"hello","World"}; try{ os=new FileOutputStream("seid.txt"); dos=new DataOutputStream(os); is=new FileInputStream("seid.txt"); dis=new DataInputStream(is); for(String j:s){ dos.writeUTF(j);} dos.flush(); //the rest code is in the next slide

while(dis.available()>0){ String k=dis.readUTF(); System.out.println(k+""); }} catch(Exception e){} finally{ if(os!=null) os.close(); if(is!=null) is.close(); if(dos!=null) dos.close(); if(dis!=null) dis.close(); }}}

Output

Order and Format


CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF.

Checking End of File


TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.

47

BufferedInputStream/ BufferedOutputStream
FileInputStream InputStream FilterInputStream

Using buffers to speed up I/O

DataInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.
48

Constructing BufferedInputStream/BufferedOutputStream
Buffer is reserved memory block. Instead of reading one byte at a time, or writing one byte at a time with buffer is possible to read whole block of data at once or to write the whole blocks of file at once. That will speed up stream reading or writing. // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize)

49

Methods of BIS
int available() This method returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. void close() This method closes this input stream and releases any system resources associated with the stream. void mark(int readlimit) This method see the general contract of the mark method of InputStream. boolean markSupported() This method tests if this input stream supports the mark and reset methods.

Methods cont
int read() This method reads the next byte of data from the input stream. int read(byte[] b, int off, int len) This method reads bytes from this byte-input stream into the specified byte array, starting at the given offset. void reset() This method repositions this stream to the position at the time the mark method was last called on this input stream.. long skip(long n) This method skips over and discards n bytes of data from this input stream.

Constructing BufferedOutputStream
// Create a BufferedOutputStream
public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize)

BOS cont
The Java.io.BufferedOutputStream class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. Class declaration
public class BufferedOutputStream extends FilterOutputStream

Field
protected byte[] buf -- This is the internal buffer where data is stored. protected int count -- This is the number of valid bytes in the buffer. protected OutputStream out -- This is the underlying output stream to be filtered.

Method of BOS
void flush() This method flushes this buffered output stream. void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this buffered output stream. void write(int b) This method writes the specified byte to this buffered output stream.

This class inherits methods from the following classes:

Java.io.FilterOutputStream Java.io.Object

Character-Oriented Streams

There are many different types of Character-Oriented Streams that is Represented by different classes within the
java.io.package

All character-oriented streams are subclasses of an abstract class Writer and Reader. Writers are subclasses of the abstract class java.io.Writer and Readers are subclasses of the abstract class java.io.Reader

All character-oriented streams inherit basic methods from their

respective superclasses Some define new methods pertinent to the type of data they provide. Character oriented streams can be used in conjunction

with byte-oriented streams:


Use InputStreamReader to "convert" an InputStream to a Reader Use OutputStreamWriter to "convert" an OutputStream to a Writer

Character-Oriented Reader Classes


The following is the byte-oriented input stream class hierarchy:
Reader

PipedReader

CharArrayReader

StringReader

BufferedReader

FilterReader

InputStreamReader

LineNumberReader

PushbackReader

FileReader

Reader Methods

There are 3 main read methods:


int read() Reads a single character. Returns it as integer int read(char[] buffer) Reads bytes and places them into buffer (max = size of buffer) returns the number of bytes read int read(char[] buffer, int offset, int length) Reads up to length bytes and places them into buffer First byte read is stored in buffer[offset] returns the number of bytes read

Reader Methods
abstract void close()
This method closes the stream and releases any system resources associated with it. This method marks the present position in the stream. This method tells whether this stream supports the mark() operation. This method reads a single character. This method reads characters into an array.

void mark(int readAheadLimit) boolean markSupported() int read()

int read(char[] cbuf)

Reader methods
abstract int read(char[] cbuf, int off, int len)
This method reads characters into a portion of an array.

int read(CharBuffer target)


This method attempts to read characters into the specified character buffer.

boolean ready()
This method tells whether this stream is ready to be read.

void reset()
This method resets the stream.

long skip(long n) This method skips characters.

Creating a Reader Object


Reader is abstract. Programmers instantiate one of its subclasses. BufferedReader Reads text from the character input stream Provides buffering to provide efficient reading of characters, arrays and lines CharArrayReader Similar to ByteArrayInputStream Constructor takes a character array. The character array provides the characters for the stream. FilterReader An abstract class for filtering character streams Filtering will be discussed later in the chapter

Creating a Reader Object


InputStreamReader This class acts as a bridge from byte streams to character streams InputStreamReader takes an InputStream parameter to its constructor The InputStreamReader reads bytes from the InputStream and translates them into characters according to the specified encoding. PipedReader Similar to PipedInputStream Connects to an Instance of PipedWriter A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedWriter Thread2 reads from the PipedReader StringReader Provides a character stream where the data is obtained from a String

Creating a Reader Object


LineNumberReader (subclass of BufferedReader)


A stream which keeps track of how many lines there have

been A line is terminated with a linefeed, carriage return or a carriage return followed immediately by a linefeed.

PushbackReader (subclass of FilterReader)


A stream which allows characters to be pushed back into

the stream after being read The number of characters which can be pushed back is specified when instantiated. Default = 1

FileReader (subclass of InputStreamReader)


A convenience class to provide a character based stream

from file. Alternatively, open the file using a FileInputStream and then pass that stream to an InputStreamReader instance.

Character-Oriented Writer and reader Classes


The following is the byte-oriented input stream class hierarchy:

Writer Methods
There are 5 main write methods: void write(int c) Writes a single character. void write(char[] buffer) Writes an array of characters void write(char[] buffer, int offset, int length) Writes a portion of an array of characters First character written is starts at buffer[offset] length indicates how many characters to write. void write(String aString) Writes aString to the stream void write(String aString, int offset, int length) Writes a portion of a String to the stream First character written is starts at aString.charAt(offset) length indicates how many characters to write.

Creating a Writer Object

Writer is abstract. Programmers instantiate one of its subclasses. BufferedWriter


Writes text to the character stream Provides buffering to provide efficient writing of characters, arrays and lines

CharArrayWriter
Similar to ByteArrayOutputStream Characters written to the stream are stored in a buffer. The buffer can be retrieved by calling toCharArray() or toString()

FilterWriter
An abstract class for writing filtered character streams Filtering will be discussed later in the chapter

Creating a Writer Object


OutputStreamWriter
This class acts as a bridge from character streams to byte streams OutputStreamWriter takes an OutputStream parameter to its constructor Characters written to the OutputStreamWriter are translated to bytes (based on the encoding) and written to the underlying OuputStream.

PipedWriter
Similar to PipedOutputStream Connects to an Instance of PipedReader A pipe represents a one-way stream through which 2 threads may communicate Thread1 writes to a PipedWriter Thread2 reads from the PipedReader

StringWriter
Characters written to this stream are collected in a StringBuffer. The StringBuffer can be used to construct a String.

Creating a Writer Object

PrintWriter
Provides print() and println() methods for standard output both print() and println() are overloaded to take a variety of types When println is used, the stream will output the appropriate sequence (either linefeed, carriage return or carriage return/linefeed) for the current platform System.out and System.err are PrintWriters

FileWriter (subclass of OutputStreamWriter)


A convenience class for writing characters to file FileWriters assume that the default character encoding is acceptable Alternatively, open the file using a FileOutputStream and then pass that stream to an OutputStreamWriter instance.

Optional

Object I/O
DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.
FileInputStream DataInputStream InputStream FilterInputStream BufferedInputStream ObjectInputStream Object FileOutputStream OutputStream FilterOutputStream ObjectOutputStream BufferedOutputStream DataOutputStream PrintStream

69

ObjectInputStream
ObjectInputStream extends InputStream and implements ObjectInput and ObjectStreamConstants.
java.io.InputStream ObjectStreamConstants java.io.DataInput java.io.ObjectInput +readObject(): Object Reads an object.

java.io.ObjectInputStream +ObjectInputStream(in: InputStream)

70

ObjectOutputStream
ObjectOutputStream extends OutputStream and implements ObjectOutput and ObjectStreamConstants.

java.io.OutputStream

ObjectStreamConstants java.io.DataOutput java.io.ObjectOutput +writeObject(o: Object): void Writes an object.

java.io.ObjectOutputStream +ObjectOutputStream(out: OutputStream)

71

Using Object Streams


You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors:
// Create an ObjectInputStream public ObjectInputStream(InputStream in) // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out)

72

The Serializable Interface


Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement Serializable. The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

73

The transient Keyword


If an object is an instance of Serializable, but it contains non-serializable instance 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 to ignore these fields when writing the object to an object stream.

74

The transient Keyword, cont.


Consider the following class:
public class Foo implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); } class A { } // A is not serializable

When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
75

Serializing Arrays
An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject. Listing 16.12 stores an array of five int values an array of three strings, and an array of two JButton objects, and reads them back to display on the console.

76

Potrebbero piacerti anche