by Debasis Samanta
The package java.io provide 23 classes, 3 interfaces, and 5 error classes that provides to manage a set of input and output streams to read data from and write data to files, strings, and otherr sources. Java streams are byte oriented and the classes defined in the java.io package can utilized to implrement more sophisticated stream manipulation. Follwing is the various component in ths package.
Classes Class BufferedInputStream Class BufferedOutputStream Class ByteArrayInputStream Class ByteArrayOutputStream Class DataInputStream Class DataOutputStream Class File Class FileDescriptor Class FileInputStream Class FileOutputStream Class FilterInputStream Class FilterOutputStream Class InputStream Class LineNumberInputStream Class OutputStream Class PipedInputStream Class PipedOutputStream Class PrintStream Class PushbackInputStream Class RandomAccessFile Class SequenceInputStream Class StreamTokenizer Class StringBufferInputStream Interfaces Interface DataInput Interface DataOutput Interface FilenameFilter Exceptions Class EOFException Class FileNotFoundException Class IOException Class InterruptedIOException Class UTFDataFormatException
The class implements a buffered input stream. By setting up a such an input stream, an application can read bytes from a stream without necessarily causing a call to the underlying system for each byte read. The data is read by blocks into a buffer; subsequent reads can access the data directly from the buffer. The structure of this class is shown as berlow :
public class java.io.BufferedInputStream extends java.io.FilterInputStream { // Member elements protected byte buf []; // An array of bytes, bufffer, where data is stored. protected int count ; // The index one greater than the index of the last valid byte in the buffer. protected int marklimit ; /* The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail. */ protected int markpos ; /* The value of the pos field at the time the last mark method was called. The value of this field is -1 if there is no current mark. */ protected int pos ; /* The current position in the buffer. This is the index of the next character to be read from the buf array. */ // Constructors public BufferedInputStream (InputStream in); /* Creates a new buffered input stream to read data from the specified input stream with a default 512-byte buffer size. public BufferedInputStream (InputStream in, int size); /* Creates a new buffered input stream to read data from the specified input stream with the specified buffer size. */ // Methods public int available () public void mark (int readlimit); public boolean markSupported (); public int read (); public int read (byte b[], int off, int len); public void reset (); public long skip (long n); } The methods are listed in Table 7.1.
Table 7.1
Method |
Description |
available () |
Determines the number of bytes that can be read from this input stream without blocking. |
mark (int readlimit) |
Marks the current position in this input stream. A subsequent call to the reset method repositions the stream at the last marked position so that subsequent reads re-read the same bytes. The readlimit arguments tells the input stream to allow that many bytes to be read before the mark position gets invalidated. |
markSupported () |
Determines if this input stream supports the mark and reset methods. The markSupported method of Buffered-Input-Stream returns true. |
read () |
Reads the next byte of data from this buffered input stream. The value byte is returned as an int 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. This method blocks until either input data is available, the end of the stream is detected, or an exception is thrown. |
read (byte b[], int off, int len) |
Reads up to len bytes of data from this buffered input stream into an array of bytes. This method blocks until some input is available. |
reset () |
Repositions this stream to the position at the time the mark method was last called on this input stream. |
skip (long n) |
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly zero. The actual number of bytes skipped is returned. |
The class implements a buffered output stream. By setting up a 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. The data is written into a buffer, and then written to the underlying stream if the buffer reaches its capacity, the buffer output stream is closed, or the buffer output stream is explicity flushed. The various components in this class is furnished as below :
public class java.io.BufferedOutputStream extends java.io.FilterOutputStream { // Member elements protected byte buf[]; // The buffer, array of bytes, where data is stored. protected int count; // The number of valid bytes in the buffer. // Constructors public BufferedOutputStream(OutputStream out); /* Creates a new buffered output stream to write data to the specified underlying output stream with a default 512-byte buffer size. */ public BufferedOutputStream(OutputStream out, int size); /* Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size. */ // Methods public void flush(); public void write(byte b[], int off, int len); public void write(int b); } The operation performed by the methods in this class is stated in Table 7.2
Table 7.2
Method |
Description |
flush() |
Flushes this buffered output stream. This forces any buffered output bytes to be written out to the underlying output stream. Throws : IOException, if an I/O error occurs. |
write(byte b[], int off, int len); |
Writes len bytes from the specified byte array starting at offset off to this buffered output stream. Throws : IOException, if an I/O error occurs. |
write(int b); |
Writes the specified byte to this buffered output stream. Throws : IOException, if an I/O error occurs. |
This class allows an application to create an input stream in which the bytes read are supplied by the contents of a byte array. Applications can also read bytes from a string by using a StringBufferInputStream.
public class java.io.ByteArrayInputStream extends java.io.InputStream { // Member elements protected byte buf[]; // The buffer, byte array containing the data. protected int count; // The index one greater than the last valid character in the input stream buffer. protected int pos; // The index of the next character to read from the input stream buffer. // Constructors public ByteArrayInputStream(byte buf[]); /* Creates a new byte array input stream which reads data from the specified byte array. The byte array is not copied. */ public ByteArrayInputStream(byte buf[], int offset, int length); /* Creates a new byte array input stream which reads data from the specified byte array. Up to length characters are to be read from the byte array, starting at the indicated offset. */ // Methods public int available(); public int read(); public int read(byte b[], int off, int len); public void reset(); public long skip(long n); } The operation performed by the various methods in ths class is stated in Table 7.3 :
Table 7.3
Method |
Description |
available() |
Determines the number of bytes that can be read from this input stream without blocking. The available method of ByteArrayInputStream returns the value of, which is the number of bytes remaining to be read from the input buffer. |
read() |
Reads the next byte of data from this input stream. The value byte is returned as an int 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. |
read(byte b[], int off, int len); |
Reads up to len bytes of data into an array of bytes from this input stream. This read method cannot block. |
reset() |
Resets this input stream to begin reading from the same position at which it first started reading from the buffer. |
skip(long n) |
Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached. |
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The structure of the class as shown below
public class java.io.ByteArrayOutputStream extends java.io.OutputStream { // Member elements protected byte buf[]; // The buffer where data is stored. protected int count; // The number of valid bytes in the buffer. // Constructors public ByteArrayOutputStream(); // Creates a new byte array output stream. public ByteArrayOutputStream(int size); /* Creates a new byte array output stream. The buffer capacity is initially 32 bytes, though its size increases if necessary. */ // Methods public void reset(); public int size(); public byte[] toByteArray(); public String toString(); public String toString(int hibyte); public void write(byte b[], int off, int len); public void write(int b); public void writeTo(OutputStream out); } The operation of the various methods are stated in Table 7.4.
Table 7.4
Method |
Description |
reset() |
Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is disdcarded. The out stream can be used again, reusing the already allocated buffer space. |
size() |
Returns the value of the count field, which is the number of valid bytes in this output stream. |
toByteArray() |
Creates a newly allocated byte array whose size is the current size of this output stream and into which the valid contents of the buffer have been copied. |
toString() |
Creates a newly allocated string whose size is the current size of this output stream and into which the valid contents of the buffer have been copied. Each character c in the resulting string is constructed from the corresponding element b in the byte array such that c == (char)(b & 0xff) |
toString(int hibyte) |
Creates a newly allocated string whose size is the current size of the output stream and into which the valid contents of the buffer have been copied. Each character c in the resulting string is constructed from the corresponding element b in the byte array such that c == (char)(((hibyte & 0xff) << 8) | (b & 0xff)) |
write(byte b[], int off, int len); |
Writes len bytes from the specified byte array starting at offset off to this byte array output stream. |
write(int b); |
Writes the specified byte to this byte array output stream. |
writeTo(OutputStream out); |
Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out write(buf, 0, count). |
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data which can later be read by a data input stream. Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. The two differences between this format and the "standard" UTF-8 format are the following:
public class java.io.DataInputStream extends java.io.FilterInputStream implements java.io.DataInput { // Constructors public DataInputStream(InputStream in); // Creates a new data input stream to read data from the specified input stream. // Methods public final int read(byte b[]); public final int read(byte b[], int off, int len); public final boolean readBoolean(); public final byte readByte(); public final char readChar(); public final double readDouble(); public final float readFloat(); public final void readFully(byte b[]); public final void readFully(byte b[], int off, int len); public final int readInt(); public final String readLine(); public final long readLong(); public final short readShort(); public final int readUnsignedByte(); public final int readUnsignedShort(); public final String readUTF(); public final static String readUTF(DataInput in); public final int skipBytes(int n); } Table 7.5 represents the operation performed by various methods in this class.
Table 7.5
Method |
Description |
read(byte b[]) |
Reads up to byte.length bytes of data from this data input stream into an array of bytes. This method blocks until some input is available. The read method of DataInputStream calls the the read method of its underlying input stream with three arguments b, 0, and b.length, and returns whatever value the method returns. |
read(byte b[], int off, int len) |
Reads up to len bytes of data from this data input stream into an array of bytes. This method blocks until some input is available. The read method of DataInputStream calls the read method of its underlying input stream with the same arguments and returns whatever value the method returns. |
readBoolean() |
Reads a boolean from this data input stream. This method reads a single byte from the underlying input stream. a value of 0 represents false. Any other value represents true. This method blocks until eother the byte is read, the end of the stream is deleted, or an exception is thrown. |
readByte() |
Reads a signed 8-bit value from this data input stream. This method reads a byte from the underlying input stream. If the byte read is b, where 0 <= b <= 255, then the result is (byte)(b). This method blocks until either the byte is read, the end of the stream is detected, or an exception is thrown. |
readChar() |
Reads a Unicode character from this data input stream. This method reads two bytes from the underlying input stream. If the bytes read, in order, are b1 and b2, where 0<= b21, b2 <= 255, then the result is equal (char)((b1 << 8) | b2) This method blocks until either the two bytes are read, the end of the stream is detected, or an exception is thrown. |
readDouble() |
Reads a double from this data input stream. This method reads a long value as if by the readLong method and then converts that long to a double using the longBitsToDouble method in class Double. This method blocks until either the eight bytes are read, the end of the stream is detected, or an exception is thrown. |
readFloat() |
Reads a float from this data input stream. This method reads an int value as if by the readInt method and then converts that into a float using the inBitsToFloat method in class Float. This method blocks until either the four bytes are read, the end of the stream is deleted, or an exception is thrown. Throws: EOFException If this input stream reaches the end before reading four bytes. |
readFully(byte b[]) |
Reads full bytes from this data input stream into the byte array. This method reads repeatedly from the underlying stream until all the bytes are read. This method blocks until either all the bytes are read, the end of the stream is deleted, or an exception is thrown. Throws : EOFException If this input stream reaches the end before reading all bytes. |
readFully(byte b[], int off, int len) |
Reads exactly len bytes from this data input stream into the byte array. This method reads repeatedly from the underlying stream until all the bytes are read. This method blocks until either all the bytes are read, the end of the stream is deleted, or an exception is thrown. Throws EOFException If this input stream reaches the end before reading all bytes. |
readInt() |
Reads a signed 32-bit integer from this data input stream. This method reads four bytes from the underlying input stream. If the read bytes are in order, b1, b2, b3, and b4, where 0<= b1, b2, b3, b4 <= 255 then the result is equal to (b1 << 24) | (b2 << 16) + (b3 << 8) + b4 This method blocks until either the four bytes are read, the end of the stream is detected, or an exception is thrown. Throws : EOFException If this input stream reaches the end before reading two bytes. |
readLine() |
Reads the next line of text from this data input stream. This method successively reads bytes from the underlying input stream until it reaches the end of a line of text.A line of text is terminated by a carriage return character ('\r'), a newline character ('\n'), a carriage return character immediately followed by a newline character, or the end of the input stream. The line-terminating character(s), if any, are included as part of the string returned. This method blocks until either a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the stream is detected, or an exception is thrown. |
readLong() |
Reads a signed 64-bit integer from this data input stream. This method reads eight bytes from the underlying input stream. If the bytes read, in order are b1, b2, b3, b4, b5, b6, b7, and b8, where 0<= b1, b2, b3, b4, b5, b6, b7, b8 <= 255 then the result is equal to ((long)b1 << 56) +((long)b2 << 48)+ ((long)b3 << 40)+ ((long)b4 << 32)+ ((long)b5 << 24) +(b6 << 16)+(b7 << 8) + b8 This method blocks until either the eight bytes are read, the end of the stream is detected, or an exception is thrown. |
readShort() |
Reads a signed 16-bit number from this data input stream. The method reads two bytes from the underlying input stream. If the two bytes read, in order are b1, b2, where each of the twop values is between 0 and 255, inclusive, then the result is equal to : (short)((b1 << 8) | b2). This method blocks until either the two bytes are read, the end of the stream is detected, or an exception is thrown. Throws: EOFException, if this input stream reaches the end before reading two bytes. |
readUnsignedByte() |
Reads an unsigned 8-bit number from this data input stream. This method reads a byte from this data input stream's underlying input stream and returns that byte. This method blocks until either the byte is read, the end of the stream is detected, or an exception is thrown. Throws: EOFException if this input stream reaches the end before reading two bytes. |
readUnsignedShort() |
Reads an unsigned 16-bit number from this data input stream. This method reads two bytes from the underlying input stream. If the bytes read are in order, b1, b2, where, 0 <= b1,b2 <= 255, then the result is equal to (b1 << 8) | b2). This method blocks until either the two bytes are read, the end of the stream is detected, or an exception is thrown. Throws: EOFException if this input stream reaches the end before reading two bytes. |
readUTF() |
Reads in a string which has been encoded using a modified UTF-8 format from this data input stream. This method calls readUTF(this). See the following method for a more complete description of the format. This method blocks until either all the bytes are read, the end of the stream is detected, or an exception is thrown. |
readUTF(DataInput in) |
Reads
in a string from the specified data input stream. The string has
been encoded using a modified using a modified UTF-8 format. The
first two bytes from are read as if by readUnsignedShort. This
value gives the number of following bytes that are in the encoded
string. (Note : not the length of the resulting string). The
following bytes are then interpreted as vbyte encoding characters
in the UTF-8 format, and are conveted into characters.This method
blocks until all the bytes are read, the end of the stream is
detected, or an exception is thrown. Throws: UTFDataFormatException if the bytes do not represent a valid UTF-8 encoding of a Unicode string.
|
skipBytes(int n) |
Skips exactly n bytes of input in the underlying input stream. this method blocks until either all the bytes are skipped, the end of the stream is detected, or an exception is thrown. Throws: EOFException, if this input stream reaches the end before skipping all the bytes. |
A data output stream 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. This class contains various constituents as shown below :
public class java.io.DataOutputStream extends java.io.FilterOutputStream implements java.io.DataOutput { // Member elements protected int written; // The number of bytes written to the data output stream. // Constructors public DataOutputStream(OutputStream out); // Creates a new data output stream to write data to the specified underlying output stream // Methods public void flush(); public final int size(); public void write(byte b[], int off, int len) public void write(int b) public final void writeBoolean(boolean v) public final void writeByte(int v) public final void writeBytes(String s) public final void writeChar(int v public final void writeChars(String s) public final void writeDouble(double v) public final void writeFloat(float v) public final void writeInt(int v) public final void writeLong(long v) public final void writeShort(int v) public final void writeUTF(String str) } The operations of the different methods are listed in Table 7.6.
Table 7.6
Method |
Description |
flush() |
Flushes this data output stream. This forces any buffered output bytes to be written out to the stream. The flush method of DataOuputStream calls the flush method of its underlying output stream. |
size() |
Determines the number of bytes written to this data output stream. |
write(byte b[], int off, int len) |
Writes len bytes from the specified byte array starting at offset off to the underlying output stream. |
write(int b) |
Writes the specified byte to the underlying output stream. |
writeBoolean(boolean v) |
Writes the specified boolean value to the underlying output stream. |
writeByte(int v) |
Writes out a byte to the underlying output stream as a one byte value. |
writeBytes(String s) |
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out. in sequence, by discarding its high eight bits. |
writeChar(int v) |
Writes a char to the underlying output stream as a two byte value, high byte first. |
writeChars(String s) |
Writes a string to the underlying output stream as a sequence of characters. Each character is written to the data outout stream as if by the writeChar method. |
writeDouble(double v) |
Converts the double argument to a long using the doubleToLongBits method in class double, and then writes the long value to the undserlying output stream as an eight byte quantity, high byte first. |
writeFloat(float v) |
Converts the float argument to an int using the floatToIntBits method in class float, and then writes the int value to the undserlying output stream as a four byte quantity, high byte first. |
writeInt(int v) |
Writes an int to the underlying output stream as four bytes, high byte first. |
writeLong(long v) |
Writes a long to the underlying output stream as eight bytes, high byte first. |
writeShort(int v) |
Writes a short to the underlying output stream as two bytes, high byte first. |
writeUTF(String s) |
Writes
out a string to the underlying output stream using UTF-8 encoding
in a machine independent manner.First, two bytes are written to
the output stream as if by the writeShort
method giving the number of bytes to follow. This value is the the
number of bytes actually written out, not the length of the
string. Following the length, each character of the string is
output, in sequence, using the UTF-8 encoding for each character. |
Instances of this class represent the name of a file or directory on the host file system. A file is specified by a path name, which can either be an absolute path name or a path name relative to the current working directory. The path name must follow the naming conventions of the host platform. The File class is intended to provide an abstraction that deals with most of the machine- dependent complexities of files and path names in a machine-independent fashion. The class as defined is stated below :
public class java.io.File extends java.lang.Object { // Member elements public final static String pathSeparator; /* The system-dependent path separator string. This field is initialized to contain the value of the system property. */ public final static char pathSeparatorChar; /* The system-dependent path separator character. This field is initialized to contain the first character of the value of the system property. This character is often used to separate file names in a sequence of files given as a path list. */ public final static String separator; /* The system-dependent path separator string. This field is initialized to contain the value of the system property. */ public final static char separatorChar; /* The system-dependent path separator string. This field is initialized to contain the first character of the value of the system property. This character separates the directory and fike components in a file name. */ // Constructors public File(File dir, String name); /* Creates a File instance that represents the file with the specified name in the specified directory. If the directory argument is null. the resulting File instance represents a file in the (system-dependent) current directory whose path name is the name argument. Otherwise, the the file instance represents a file whose path nmae is the path nmae of the directory, followed by the separator charactor, followed by the name argument. */ public File(String path); /* Creates a File instance that represents the file whose path name is the given path argument. Throws : NullPointerException, If the file path is equal to null. */ public File(String path, String name); /* Creates a File instance whose path name is the pathname of the specified directory, followed by the separator character, followed by the name argument. */ // Methods public boolean canRead(); public boolean canWrite(); public boolean delete(); public boolean equals(Object obj); public boolean exists(); public String getAbsolutePath(); public String getName(); public String getParent(); public String getPath(); public int hashCode(); public boolean isAbsolute(); public boolean isDirectory(); public boolean isFile(); public long lastModified(); public long length(); public String[] list(); public String[] list(FilenameFilter filter); public boolean mkdir(); public boolean mkdirs(); public boolean renameTo(File dest); public String toString(); } The description of the methods is listed in Table 7.7.
Table 7.7
Instances of the file descriptor class serve as an opaque handle to the underlying machine- specific structure representing an open file or an open socket. Applications should not create their own file descriptors. This class is shown below :
public final class java.io.FileDescriptor extends java.lang.Object { // Fields public final static FileDescriptor err; // A handle to the standard error stream. public final static FileDescriptor in; // A handle to the standard input stream public final static FileDescriptor out; // A handle to the standard output stream. // Constructors public FileDescriptor( ); // The default constructor. // Methods public boolean valid( ); /* This method returns true if the file descriptor object represents a valid, open file or socket; false otherwise.*/ }
This class is to manage a file input stream as an input stream for reading data from a File or from a FileDescriptor.
public class java.io.FileInputStream extends java.io.InputStream { // Constructors public FileInputStream(File file); /* Creates an input file stream to read from the specified File object. Throws : FileNotFoundException,if the file is not found. */ public FileInputStream(FileDescriptor fdObj); /* Creates an input file stream to read from the specified file descriptor. Throws : SecurityException if a security manager exists, its checkRead method is called with the file descriptor to see if the application is allowed to read from the specified file descriptor. This may result in a security exception. */ public FileInputStream(String name); /* Throws : FileNotFoundException, if the file is not found and SecurityException, if a security manager exists, its checkRead method is called with the name argument t to see if the application is allowed read access to the file. This may result in a security exception. */ // Methods public int available(); public void close(); protected void finalize(); public final FileDescriptor getFD(); public int read(); public int read(byte b[]); public int read(byte b[], int off, int len); public long skip(long n); } Table 7.8 lists the operations performed by various methods in this class.
Table 7.8
Method |
Description |
available() |
Returns the number of bytes that can be read from this file input stream without blocking. |
close() |
Closes this file input stream and releases any system resources associated with the stream. |
finalize() |
This finalize method ensures that the close method of this file input stream is called when there are no more references to it. |
getFD() |
Returns the file descriptor object. |
read() |
Reads a byte of data from this input stream. This method blocks if no input is yet available. It returns -1 if the end of the file is reached. |
read(byte b[]) |
Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. It returns -1 is there is no more data because the end of the file has been reached. |
read(byte b[], int off, int len) |
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until some input is available.It returns -1 if is there is no more data because the end of the file has been reached. |
skip(long n) |
Skips over and discards n bytes of data from the input stream. The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly zero. The actual number of bytes skipped is returned. |
A file output stream is an output stream for writing data to a File or to a FileDescriptor.
public class java.io.FileOutputStream extends java.io.OutputStream { // Constructors public FileOutputStream(File file); /* Creates an file output stream to write to the specified File object. Throws : IOException, If the file could not be opened for writing. It also throws SecurityException, if a security manager exists, its checkWrite method is called with the path name of the File argument to see if the application is allowed write access to the file. This may result in a security exception. */ public FileOutputStream(FileDescriptor fdObj); /* Creates an output file stream to write to the specified file descriptor. Throws : SecurityException, if a security manager exists, its checkWrite method is called with the file descriptor to see if the application is allowed to write to the specified file descriptor. */ public FileOutputStream(String name); /* Creates an output file stream to write to the file with the specified name. Throws : IOException, if the file could not be opened for writing. It also throws SecurityException, if a security manager exists, its checkWrite method is called with the name argument to see if the application is allowed write access to the file. */ // Methods public void close(); protected void finalize(); public final FileDescriptor getFD(); public void write(byte b[]); public void write(byte b[], int off, int len); public void write(int b); } The methods are being tabulated in Table 7.9.
Table 7.9
This class is the superclass of all classes that filter input streams. These streams sit on top of an already existing input stream (the underlying input stream), but provide additional functionality. The class structure is shown as below :
public class java.io.FilterInputStream extends java.io.InputStream { // Member elements protected InputStream in; // This indicates the input stream under consideration. // Constructors protected FilterInputStream(InputStream in); // Creates an input stream filter built on top of the specified input stream. // Methods public int available(); public void close(); public void mark(int readlimit); public boolean markSupported(); public int read(); public int read(byte b[]); public int read(byte b[], int off, int len); public void reset(); public long skip(long n); } The methods are described in Table 7.10.
Table 7.10
This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream), but provide additional functionality.
The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream. Subclasses of FilterOutputStream may further override some of these methods as well as provide additional methods and fields. The class structure is as below :
public class java.io.FilterOutputStream extends java.io.OutputStream { // Member elements protected OutputStream out; // The output stream under consideration. // Constructors public FilterOutputStream(OutputStream out); // Creates an output stream filter built on top of the specified underlying output stream. // Methods public void close(); public void flush(); public void write(byte b[]); public void write(byte b[], int off, int len); public void write(int b); } Table 7.11 describes the methods of this class :
Table 7.11
Method |
Description |
close() |
Closes this output stream and releases any system resources associated with the stream. The close method of FilterOutputStream calls its flush method and then calls the close method of its underlying output stream. |
flush() |
Flushes this output stream and forces any buffered output bytes to be written out to the stream. The flush method of FilterOutputStream calls the flush method of it underlying output stream |
write(byte b[]) |
The write method of FilterOutputStream calls its write method of three arguments with the arguments b, 0, and b.length. |
write(byte b[], int off, int len) |
Writes len bytes from the specified byte array starting at offset off to this output stream. Note that this method does not call the write method of its underlying input stream with the same arguments. Subclasses of FilterOutputStream should provide a more efficient implementation of this method. |
write(int b) |
Writes the specified byte to this output stream. The write method of FilterOutputStream calls the write method of its underlying output stream. |
This class is an abstract class that is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.
public abstract class java.io.InputStream extends java.lang.Object { // Constructors public InputStream(); // The default constructor. This constructor is only called by subclasses. // Methods public int available(); public void close(); public void mark(int readlimit); public boolean markSupported(); public abstract int read(); public int read(byte b[]); public int read(byte b[], int off, int len); public void reset(); public long skip(long n); } Table 7.12 lists the methods.
Table 7.12
A line is a sequence of bytes ending with either a carriage return character ('\r'), a newline character ('\n'), or a carriage return character followed immediately by a line feed character. In all three cases the line terminating character(s) are returned as a single newline character.
This class is an input stream filter that provides the added functionality of keeping track of the current line number.The line number begins at zero, and is incremented by 1 when a read returns a newline character.
The class is shown as below :
The class is shown as below : public class java.io.LineNumberInputStream extends java.io.FilterInputStream { // Constructors public LineNumberInputStream(InputStream in); /* Constructs a new line number input stream that reads its input from the specified input stream. */ // Methods public int available(); public int getLineNumber(); public void mark(int readlimit); public int read(); public int read(byte b[], int off, int len); public void reset(); public void setLineNumber(int lineNumber); public long skip(long n); } The desription of these metods is given in Table 7.13.
Table 7.13
This class is an abstract class that is the superclass of all classes representing an output stream of bytes. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. The class is given below :
public abstract class java.io.OutputStream extends java.lang.Object { // Constructors public OutputStream(); // The default constructor. // Methods public void close(); public void flush(); public void write(byte b[]); public void write(byte b[], int off, int len); public abstract void write(int b); } The Table 7.14 is to list the function of these methods.
Table 7.14
Method |
Description |
close() |
Closes this output stream and releases any system resources associated with this stream. |
flush() |
Flushes this output stream and forces any buffered output bytes to be written out. |
write(byte b[]) |
Writes b.length bytes from the specified byte array to this output stream. |
write(byte b[], int off, int len) |
Writes len bytes from the specified byte array starting at offset off to this output stream. |
write(int b) |
Writes the specified byte to this output stream. |
A piped input stream is the receiving end a communications pipe. Two threads can communicate by having one thread send data through a piped output stream and having the other thread read the data through a piped input stream.
public class java.io.PipedInputStream extends java.io.InputStream { // Constructors public PipedInputStream(); /* Creates a piped input stream that is not yet connected to a piped output stream. It must be connected to a piped output stream, either by the receiver or the sender, before being used. */ public PipedInputStream(PipedOutputStream src); /*Creates a piped input stream connected to the specified piped output stream.Throws IOException , If an I/O error occurs. */ // Methods public void close(); public void connect(PipedOutputStream src); public int read(); public int read(byte b[], int off, int len); } The functions description is given in Table 7.15
Table 7.15
Method |
Description |
close() |
Closes this piped input stream and releases any system resources associated with the stream and close in class InputStream. |
connect(PipedOutputStream src) |
Connects this piped input stream to a sender. |
read() |
Reads the next byte of data from this piped input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because this end of the stream has been reached, the value -1 is returned. This method blocks until either input data is available, the end of the stream is detected, or an exception is thrown. It overrides read in class InputStream and throws IOExeption , if the pipe is broken. Returns: the next byte of data, or -1 if the end of the stream is reached. |
read(byte b[], int off, int len) |
Reads up to len bytes of data from this piped input stream into an array of bytes. This method blocks until at least one byte of input is available. It overrides read in class InputStream. Returns :the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached. and throws an IOException if an I/O error occurs. |
A piped output stream is the sending end a communications pipe. Two threads can communicate by having one thread send data through a piped output stream and having the other thread read the data through a piped input stream.
public class java.io.PipedOutputStream extends java.io.OutputStream { // Constructors public PipedOutputStream(); /* Creates a piped output stream that is not yet connected to a piped input stream. It must be connected to a piped input stream, either by the receiver or the sender, before being used. */ public PipedOutputStream(PipedInputStream snk); // Creates a piped output stream connected to the specified piped input stream snk. // Methods public void close(); public void connect(PipedInputStream snk); public void write(byte b[], int off, int len); public void write(int b); } The metods are described in Table 7.16.
Table 7.16
Method |
Description |
close() |
Closes this piped output stream and releases any system resources associated with this stream. |
connect(PipedInputStream snk) |
Connects this piped output stream to a receivier. |
write(byte b[], int off, int len) |
Writes len bytes from the specified byte array starting at offset off to this piped output stream. |
write(int b) |
Writes the specified byte to the piped output stream. |
A print stream implements an output stream filter that provides convenient methods for printing types other than bytes and arrays of bytes. In addition, the print stream overrides many of the InputStream methods so as not to throw an IOException. Instead, an I/O exception causes an internal flag to be set, which the application can check by a call to the checkError method.Only the lower 8 bits of any 16-bit quantity are printed to the stream.
An application can specify at creation time whether a print stream should be flushed every time a newline character is written
Here are some examples of the use of a print stream: System.out.println("Hello world!"); System.out.print("x = "); System.out.println(x); System.out.println("y = " + y); Following is the various components in it.
public class java.io.PrintStream extends java.io.FilterOutputStream { // Constructors public PrintStream(OutputStream out); /* Constructs a new print stream that writes its output to the specified underlying output stream. */ public PrintStream(OutputStream out, boolean autoflush); /* Constructs a new print stream that writes its output to the specified underlying output stream. In addition, if the autoflush flag is true, then the underlying output stream's flush method is called any time a newline character is printed. */ // Methods public boolean checkError(); public void close(); public void flush(); public void print(boolean b); public void print(char c); public void print(char s[]); public void print(double d); public void print(float f); public void print(int i); public void print(long l); public void print(Object obj); public void print(String s); public void println(); public void println(boolean b); public void println(char c); public void println(char s[]); public void println(double d); public void println(float f); public void println(int i); public void println(long l); public void println(Object obj); public void println(String s); public void write(byte b[], int off, int len); public void write(int b); } The methods are summarized in Table 7.17.
Table 7.17
This class is an input stream filter that provides a one-byte push back buffer. This feature allows an application to "unread" the last character that it read. The next time that a read is performed on the input stream filter, the "unread" character is re-read.
This functionality is useful in situations where it is useful for a fragment of code to read an indefinite number of data bytes that are delimited by particular byte values; after reading the terminating byte, the code fragment can "unread" it, so that the next read operation on the input stream will re-read the byte that was pushed back.
public class java.io.PushbackInputStream extends java.io.FilterInputStream { // Member element protected int pushBack; /* A character that has been "unread" and that will be the next byte read. The value -1 indicates no character in the buffer. */ // Constructors public PushbackInputStream(InputStream in); /* Constructs a new pushback input stream that reads its input from the specified input stream. */ // Methods public int available(); public boolean markSupported(); public int read(); public int read(byte b[], int off, int len); public void unread(int ch); } The metods are explained in Table 7.18.
Table 7.18
This is the one important class known for I/O manipulation. Instances of this class support both reading and writing to a random access file. An application can modify the position in the file at which the next read or write occurs. The structure of this class is as shown below :
public class java.io.RandomAccessFile extends java.lang.Object implements java.io.DataOutput java.io.DataInput { // Constructors public RandomAccessFile(File file, String mode); /* Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. The mode argument must either be equal to "r" or to "rw", indicating either to open the file for input, or for both input and output, respectively. */ public RandomAccessFile(String name, String mode); /* Creates an random access file stream to read from, and optionally to write to, a file with the specified name. The mode argument must either be equal to "r" or "rw", indicating either to open the file for input or for both input and output. */ /* Constructors in this class may throw the exceptions as indicated below : Throws : IOException, If an I/O error occurs. Throws IllegalArgumentException, f the mode argument is not equal to "r" or to "rw". Throws : SecurityException, If a security manager exists, its checkRead method is called with the path name of the File argument to see if the application is allowed read access to the file. If the mode argument is equal to "rw", its checkWrite method also is called with the path name to see if the application is allowed write access to the file. */ // Methods public void close(); public final FileDescriptor getFD(); public long getFilePointer(); public long length(); public int read(); public int read(byte b[]); public int read(byte b[], int off, int len); public final boolean readBoolean(); public final byte readByte(); public final char readChar(); public final double readDouble(); public final float readFloat(); public final void readFully(byte b[]); public final void readFully(byte b[], int off, int len); public final int readInt(); public final String readLine(); public final long readLong(); public final short readShort(); public final int readUnsignedByte(); public final int readUnsignedShort(); public final String readUTF(); public void seek(long pos); public int skipBytes(int n); public void write(byte b[]); public void write(byte b[], int off, int len); public void write(int i); public final void writeBoolean(boolean v); public final void writeByte(int v); public final void writeBytes(String s); public final void writeChar(int v); public final void writeChars(String s); public final void writeDouble(double v); public final void writeFloat(float v); public final void writeInt(int v); public final void writeLong(long v); public final void writeShort(int v); public final void writeUTF(String str); } The function of various methods in this class is stated in Table 7.19.
Table 7.19
Note : 1) All the read methods block until either the byte is read, the end of the stream is detected, or an exception is thrown. 2) All the read methods throws an EOFException, if an end of file encounters. 3) All the methods in this class throws IOException if I/O errors occur.
The sequence input stream class allows an application to combine several input streams serially and make them appear as if they were a single input stream. Each input stream is read from, in turn, until it reaches the end of the stream. The sequence input stream class then closes that stream and automatically switches to the next input stream.
public class java.io.SequenceInputStream extends java.io.InputStream { // Constructors public SequenceInputStream(Enumeration e); /* Constructs a new sequence input stream initialized to the specified enumeration of input streams. Each object in the enumeration must be an InputStream. */ public SequenceInputStream(InputStream s1, InputStream s2); /* Constructs a new sequence input stream initialized to read first from the input stream s1, and then from the input stream s2. */ // Methods public void close(); public int read(); public int read(byte buf[], int pos, int len); } Methods are listed in Table 7.20.
Table 7.20
Method |
Description |
close() |
Closes this input stream and releases any system resources associated with the stream. |
read() |
Reads the next byte of data from this input stream. The byte is returned as an int 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. This method blocks until either input data is available, the end of the stream is detected, or an exception is thrown. |
read(byte buf[], int pos, int len) |
Reads up to len bytes of data from this input stream into an array of bytes. This method blocks until at least one byte of input is available. If the first argument is null, up to len bytes are read and discarded. |
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.
Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: whitespace, alphabetic, numeric, tring quote, and comment character. Each character can have zero or more of these attributes. In addition an instance has four flags. These flags indicate:
A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF. Let us see the structure of this class.
public class java.io.StreamTokenizer extends java.lang.Object { // Member elements public double nval; /* If the current token is a number, this field contains the value of that number. The current token is a number when the value of the ttype field is TT_NUMBER. */ public String sval; /* If the current token is a word token, this field contains a string giving the characters of the word token. When the current token is a quoted string token, this field contains the body of the string. The current token is a word when when the value of the ttype field is TT_WORD. */ public int ttype; /* After a call to the nextToken method , this field contains the type of the token just read. For a single character token, its value is the single character, converted to an integer. For a quoted string token its value is the quote character. Otherwise, its value is one of the following: TT_WORD indicates that the token is a word. TT_NUMBER indicates that the token is a number. TT_EOL indicates that the end of line has been read. The field can only have this value if the eolIsSignficant method has been called with the argument true. TT_EOF indicates that the end of the input stream has been reached. */ // Constructors public StreamTokenizer(InputStream i); /* Creates a stream tokenizer that parses the specified input stream. The stream tokenizer is initialized to the following default state: All byte values 'A' through 'Z', 'a' through 'z', and '\u00A0' through '\u00FF' are considered to be alphabetic. All byte values '\u0000' through '\u0020' are considered to be whitespace. '/' is a comment character. Single quote '\'' and double quote '"' are string quote characters. Numbers are parsed . End of lines are not treated as whitespace, not as separate tokens. C-style and C++-style comments are not recognized. */ // Methods public void commentChar(int ch); public void eolIsSignificant(boolean flag); public int lineno(); public void lowerCaseMode(boolean fl); public int nextToken(); public void ordinaryChar(int ch); public void ordinaryChars(int low, int hi); public void parseNumbers(); public void pushBack(); public void quoteChar(int ch); public void resetSyntax(); public void slashStarComments(boolean flag); public String toString(); public void whitespaceChars(int low, int hi); public void wordChars(int low, int hi); } All these methods are listed in Table 7.21.
Table 7.21
This class allows an application to create an input stream in which the bytes read are supplied by the contents of a string. Applications can also read bytes from a byte array by using a ByteArrayInputStream. Only the low eight bits of each character in the string are used by this class.
public class java.io.StringBufferInputStream extends java.io.InputStream { // Member elements protected String buffer; // The string from which bytes are read. protected int count; // The number of valid characters in the input stream buffer. protected int pos; // The index of the next character to read from the input stream buffer. // Constructors public StringBufferInputStream(String s); // Creates a string input stream to read data from the specified string. // Methods public int available(); public int read(); public int read(byte b[], int off, int len); public void reset(); public long skip(long n); } Methods are described in Table 7.22.
Table 7.22
Method |
Description |
available() |
Determines the number of bytes that can be read from the input stream without blocking. |
read() |
Reads the next byte of data from this input stream. The value byte is returned as an int 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. |
read(byte b[], int off, int len) |
Reads up to len bytes of data from this input stream into an array of bytes or returns -1 is there is no more data because the end of the stream has been reached.. |
reset() |
Resets the input stream to begin reading from the first character of this input stream's underlying buffer. |
skip(long n) |
Skips n bytes of input from this input stream. Fewer bytes might be skipped if the end of the input stream is reached. |
The data input interface is implemented by streams that can read primitive Java data types from a stream in a machine-independent manner. The constitutents in this interface is listed below :
public interface java.io.DataInput { // Methods public abstract boolean readBoolean(); public abstract byte readByte(); public abstract char readChar(); public abstract double readDouble(); public abstract float readFloat(); public abstract void readFully(byte b[]); public abstract void readFully(byte b[], int off, int len); public abstract int readInt(); public abstract String readLine(); public abstract long readLong(); public abstract short readShort(); public abstract int readUnsignedByte(); public abstract int readUnsignedShort(); public abstract String readUTF(); public abstract int skipBytes(int n); } The methods are described in Table 7.23.
Table 7.23
Method |
Description |
readBoolean() |
Reads a boolean value from the input stream. |
readByte() |
Reads a signed eight-bit value from the input stream. |
readChar() |
Reads a Unicode char value from the input stream. |
readDouble() |
Reads a double value from the input stream. |
readFloat() |
Reads a float value from the input stream, high byte. |
readFully(byte b[]) |
Reads b.length bytes into the byte array. This method blocks until all the bytes are read. |
readFully(byte b[], int off, int len) |
Reads b.len bytes into the byte array. This method blocks until all the bytes are read. |
readInt() |
Reads an int value from the input stream. |
readLine() |
Reads the next line of text from the input stream. |
readLong() |
Reads a long value from the input stream. |
readShort() |
Reads a 16-bit value from the input stream. |
readUnsignedByte() |
Reads an unsigned eight-bit value from the input stream. |
readUnsignedShort() |
Reads an unsigned 16-bit value from the input stream. |
readUTF() |
Reads in a string that has been encoded using a modified UTF-8 format. |
skipBytes(int n) |
Skips exactly n bytes of input. |
The data output interface is implemented by streams that can write primitive Java data types to an output stream in a machine-independent manner. The interface is as shown below :
public interface java.io.DataOutput { // Methods public abstract void write(byte b[]); public abstract void write(byte b[], int off, int len); public abstract void write(int i); public abstract void writeBoolean(boolean v); public abstract void writeByte(int v); public abstract void writeBytes(String s); public abstract void writeChar(int v); public abstract void writeChars(String s); public abstract void writeDouble(double v); public abstract void writeFloat(float v); public abstract void writeInt(int v); public abstract void writeLong(long v); public abstract void writeShort(int v); public abstract void writeUTF(String str); } The methods are described in Table 7.24.
Table 7.24
Method |
Description |
write(byte b[]) |
Writes b.length bytes from the specified byte array to this output stream. |
write(byte b[], int off, int len) |
Writes len bytes from the specified byte array starting at offset off to this output stream |
write(int i) |
Writes the specified byte to this data output stream. |
writeBoolean(boolean v) |
Writes a boolean value to this output stream. |
writeByte(int v) |
Writes an 8-bit value to this output stream. |
writeBytes(String s) |
Writes out the string to this output stream as a sequence of bytes. |
writeChar(int v) |
Writes a char value of v to this output stream. |
writeChars(String s) |
Writes a string to this output stream as a sequence of characters. |
writeDouble(double v) |
Writes a double value to this output stream. |
writeFloat(float v) |
Writes a float value to this output stream. |
writeInt(int v) |
Writes an int value to this output stream. |
writeLong(long v) |
Writes a long value to this output stream |
writeShort(int v) |
Writes a 16-bit value to this output stream |
writeUTF(String str) |
Writes out a Unicode string that by encoded it using modified UTF-8 format. |
Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in the list method of class File and by the Abstract Window Toolkit's file dialog component.
public interface java.io.FilenameFilter { // Methods public abstract boolean accept(File dir, String name); /* Determines whether a specified file should be included in a file list. Returns: true if name should be included in file list; false otherwise. */ }
Signals that an end-of-file has been reached unexpectedly during input. This exception is mainly used by data input streams, which generally expect a binary file in a specific format, and for which an end-of-stream is an unusual condition. Most other input streams return a special value on end of stream.
public class java.io.EOFException extends java.io.IOException { // Constructors public EOFException(); // Constructs an EOFException with no detail message. public EOFException(String s); // Constructs an EOFException with the specified detail message. }
Signals that a file could not be found.
public class java.io.FileNotFoundException extends java.io.IOException { // Constructors public FileNotFoundException(); // Constructs a FileNotFoundException with no detail message. public FileNotFoundException(String s); // Constructs a FileNotFoundException with the specified detail message. }
Signals that an I/O exception of some sort has occurred.
public class java.io.IOException extends java.lang.Exception { // Constructors public IOException(); // Constructs an IOException with no detail message. public IOException(String s); // Constructs an IOException with the specified detail message. }
Signals that an I/O operation has been interrupted.
public class java.io.InterruptedIOException extends java.io.IOException { // Member elements public int bytesTransferred; /* Reports how many bytes had been transferred as part of the IO operation before it was interrupted. */ // Constructors public InterruptedIOException(); // Constructs an InterruptedIOException with no detail message. public InterruptedIOException(String s); // Constructs an InterruptedIOException with the specified detail message. }
Signals that a malformed UTF-8 string has been read in a data input stream or by any class that implements the data input interface
public class java.io.UTFDataFormatException extends java.io.IOException { // Constructors public UTFDataFormatException(); // Constructs an UTFDataFormatException with no detail message. public UTFDataFormatException(String s); // Constructs an UTFDataFormatException with the specified detail message. }