|
Generated by JDiff |
||||||||
PREV PACKAGE NEXT PACKAGE FRAMES NO FRAMES |
This file contains all the changes in documentation in the packagejava.io
as colored differences. Deletions are shownlike this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.
ABufferedInputStream
adds functionality to another input stream-namely the ability to buffer the input and to support themark
andreset
methods. When theBufferedInputStream
is created an internal buffer array is created. As bytes from the stream are read or skipped the internal buffer is refilled as necessary from the contained input stream many bytes at a time. Themark
operation remembers a point in the input stream and thereset
operation causes all the bytes read since the most recentmark
operation to be reread before new bytes are taken from the contained input stream. @author Arthur van Hoff @version 1.41 0242 12/0203/0001 @since JDK1.0
The 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. The data is written into an internal 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 explicitly flushed. @author Arthur van Hoff @version 1.Class BufferedOutputStream, constructor BufferedOutputStream(OutputStream, int)27 0229 12/0203/0001 @since JDK1.0
Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size. @param out the underlying output stream. @param size the buffer size. @exception IllegalArgumentException if size <= 0.
Read text from a character-input stream buffering characters so as to provide for the efficient reading of characters arrays and lines.Class BufferedReader, int read()The buffer size may be specified or the default size may be used. The default is large enough for most purposes.
In general each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly such as FileReaders and InputStreamReaders. For example
BufferedReader in = new BufferedReader(new FileReader("foo.in"));will buffer the input from the specified file. Without buffering each invocation of read() or readLine() could cause bytes to be read from the file converted into characters and then returned which can be very inefficient.Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader. @see FileReader @see InputStreamReader @version 1.
2728 01/0212/0903 @author Mark Reinhold @since JDK1.1
Read a single character. @return The character read as an integer in the range 0 to 65535 (0x00-0xffff) or -1 if the end of the stream has been reached @exception IOException If an I/O error occurs
Write text to a character-output stream buffering characters so as to provide for the efficient writing of single characters arrays and strings.The buffer size may be specified or the default size may be accepted. The default is large enough for most purposes.
A newLine() method is provided which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.
In general a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly such as FileWriters and OutputStreamWriters. For example
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));will buffer the PrintWriter's output to the file. Without buffering each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file which can be very inefficient. @see PrintWriter @see FileWriter @see OutputStreamWriter @version 1.22 0023 01/0212/0203 @author Mark Reinhold @since JDK1.1
AClass ByteArrayInputStream, constructor ByteArrayInputStream(byte[], int, int)ByteArrayInputStream
contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by theread
method.Closing a ByteArrayInputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException. @author Arthur van Hoff @version 1.
35 0239 12/0203/0001 @see java.io.StringBufferInputStream @since JDK1.0
CreatesClass ByteArrayInputStream, void close()ByteArrayInputStream
that usesbuf
as its buffer array. The initial value ofpos
isoffset
and the initial value ofcount
isoffset+len
. The buffer array is not copied.Note that if bytes are simply read from the resulting input stream elements buf[pos] through buf[pos+len-1] will be read; however if aTheresetbuffer'soperationmark isperformed then bytes buf[0] through buf[pos-1] willsetthen becometoavailable for inputthe specified offset. @param buf the input buffer. @param offset the offset in the buffer of the first byte to read. @param length the maximum number of bytes to read from the buffer.
Class ByteArrayInputStream, void mark(int)Closes thisClosing ainputByteArrayInputStreamstreamhas no effect. Theandmethodsreleasesin thisany system resources associated withclass can be called after the stream has been closed without generating an IOException.
Set the current marked position in the stream. ByteArrayInputStream objects are marked at position zero by default when constructed. They may be marked at another position within the buffer by this method.Class ByteArrayInputStream, void reset()If no mark has been set then the value of the mark is the offset passed to the constructor (or 0 if the offset was not supplied). @since JDK1.1
Resets the buffer to the marked position. The marked position isClass ByteArrayInputStream, int markthe beginning0 unless another position was marked.The value ofor an offsetposwasis set to 0specified in the constructor.
The currently marked position in the stream. ByteArrayInputStream objects are marked at position zero by default when constructed. They may be marked at another position within the buffer by themark()
method. The current buffer position is set to this point by thereset()
method.If no mark has been set then the value of mark is the offset passed to the constructor (or 0 if the offset was not supplied). @since JDK1.1
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 data can be retrieved usingClass ByteArrayOutputStream, void close()toByteArray()
andtoString()
.Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException. @author Arthur van Hoff @version 1.
43 0245 12/0203/0001 @since JDK1.0
Closes thisClosing aoutputByteArrayOutputStreamstream andhas noreleaseseffect.any system resources associated with thisThe methods in this class canstream.beA closed stream cannot perform output operations and cannot becalled after the stream has been closed without generating anreopenedIOException.
This class implements a character buffer that can be used as a character-input stream. @author Herb Jellinek @version 1.Class CharArrayReader, int count15 0217 12/0203/0001 @since JDK1.1
Thenumberindex ofvalidthecharacters in theend of this buffer. There is not valid data at or beyond this index.
This class implements a character buffer that can be used as an Writer. The buffer automatically grows when data is written to the stream. The data can be retrieved using toCharArray() and toString(). @author Herb Jellinek @version 1.15 0216 12/0203/0001 @since JDK1.1
Base class for character conversion exceptions. @author Asmus Freytag @version 1.12 0213 12/0203/0001 @since JDK1.1
TheClass DataInput, String readLine()DataInput
interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types. There is also a facility for reconstructing aString
from data in Java modified UTF-8 format.It is generally true of all the reading routines in this interface that if end of file is reached before the desired number of bytes has been read an
EOFException
(which is a kind ofIOException
) is thrown. If any byte cannot be read for any reason other than end of file anIOException
other thanEOFException
is thrown. In particular anIOException
may be thrown if the input stream has been closed. @author Frank Yellin @version 1.16 0219 12/0203/0001 @see java.io.DataInputStream @see java.io.DataOutput @since JDK1.0
Reads the next line of text from the input stream. It reads successive bytes converting each byte separately into a character until it encounters a line terminator or end of file; the characters read are then returned as aClass DataInput, int skipBytes(int)String
. Note that because this method processes bytes it does not support input of the full Unicode character set.If end of file is encountered before even one byte can be read then
null
is returned. Otherwise each byte that is read is converted to typechar
by zero-extension. If the character'\n'
is encountered it is discarded and reading ceases. If the character'\r'
is encountered it is discarded and if the following byte converts to the character'\n'
then that is discarded also; reading then ceases. If end of file is encountered before either of the characters'\n'
and'\r'
is encountered reading ceases. Once reading has ceased aString
is returned that contains all the characters read and not discarded taken in order. Note that every character in this string will have a value less than\u0100
that is(char)256
. @returnifthethisnext line of text from the input streamreachesornull
if the end of file is encountered beforereading all thea byte canbytesbe read. @exception IOException if an I/O error occurs.
Makes an attempt to skip overn
bytes of data from the input stream discarding the skipped bytes. However it may skip over some smaller number of bytes possibly zero. This may result from any of a number of conditions; reaching end of file beforen
bytes have been skipped is only one possibility. This method never throws anEOFException
. The actual number of bytes skipped is returned. @param n the number of bytes to be skipped. @return the number of bytesskipped which is always n. @exception EOFException ifactuallythis stream reaches the end before skipping all the bytesskipped. @exception IOException if an I/O error occurs.
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 that can later be read by a data input stream.Class DataInputStream, int read(byte[])Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information see X/Open Company Ltd. "File System Safe UCS Transformation Format (FSS_UTF)" X/Open Preliminary Specification Document Number: P316. This information also appears in ISO/IEC 10646 Annex P.) Note that in the following tables the most significant bit appears in the far left-hand column.
All characters in the range
'\u0001'
to'\u007F'
are represented by a single byte:
0 bits 06-70The null character
'\u0000'
and characters in the range'\u0080'
to'\u07FF'
are represented by a pair of bytes:
1 1 0 bits 6-10-61 0 bits 0-5-0
Characters in the range'\u0800'
to'\uFFFF'
are represented by three bytes:
1 1 1 0 bits 12-15-121 0 bits 6-11-61 0 bits 0-5-0The two differences between this format and the "standard" UTF-8 format are the following:
@author Arthur van Hoff @version 1.
- The null byte
'\u0000'
is encoded in 2-byte format rather than 1-byte so that the encoded strings never have embedded nulls.- Only the 1-byte 2-byte and 3-byte formats are used.
51 0256 12/2803/0001 @see java.io.DataOutputStream @since JDK1.0
@param b the buffer into which the data is read. @return the total number of bytes read into the buffer orSeeReads some number of bytes from the contained input stream and stores them into thegeneralbuffer arrayb
. The number of bytes actually read is returned as an integer. This method blocks until input data is availablecontractend of file is detected or an exception is thrown.If
the length ofb
is null aNullPointerException
is thrown. Ifb
is zero then no bytes are read and0
methodis returned; otherwise there is an attempt to read at least one byte. If no byte is available because the stream is at end of file the value-1
is returned; otherwise at least one byte is read and stored into.
DataInputbThe
Bytesfirstforbyte readthis operationis storedareinto elementb[0]
the next one intob[1]
and so on. The number of bytes readfromis at most equal to thecontainedlength ofb
. Letk
be the number of bytes actually read; these bytes will be stored in elementsb[0]
throughb[k-1]
leaving elementsb[k]
throughb[b.length-1]
unaffected.If the first byte cannot be read for any reason other than end of file then an
input stream has been closed.IOException
is thrown. In particular anIOException
is thrown if theThe
read(b)
method has the same effect as:.length)read(b 0 b
-1
if there is no more data because the end of the stream has been reached. @exception IOException if an I/O error occurs. @see java.io.FilterInputStream#in @see java.io.InputStream#read(byte[] int int)
Class DataInputStream, int read(byte[], int, int)SeeReadstheup togenerallen
contractbytes of data from the contained input stream into an array of bytes. An attempt is made to read as many aslen
bytes but a smaller number may be read possibly zero. The number of bytes actually read is returned as an integer.This
method blocks until input data is available end of file is detected or an exception is thrown.If
b
isnull
ais thrown.
DataInputNullPointerException
BytesIfforoff
thisis negative orlen
is negative oroff+len
is greater than the length of the arrayoperationb
then anIndexOutOfBoundsException
is thrown.If
len
is zero then no bytes are readfromand0
is returned; otherwise there is an attempt to read at least one byte. If no byte is available because thecontainedstream is at end of file the value-1
is returned; otherwise at least one byte is read and stored intob
.The first byte read is stored into element
b[off]
the next one intob[off+1]
and so on. The number of bytes read is at most equal tolen
. Let k be the number of bytes actually read; these bytes will be stored in elementsb[off]
throughb[off+
k-1]
leaving elementsb[off+
k]
throughb[off+len-1]
unaffected.In every case elements
b[0]
throughb[off]
and elementsb[off+len]
throughb[b.length-1]
are unaffected.If the first byte cannot be read for any reason other than end of file then an
input stream has been closed. @param b the buffer into which the data is read. @param off the start offset of the data. @param len the maximum number of bytes read. @return the total number of bytes read into the buffer orIOException
is thrown. In particular anIOException
is thrown if the-1
if there is no more data because the end of the stream has been reached. @exception IOException if an I/O error occurs. @see java.io.FilterInputStream#in @see java.io.InputStream#read(byte[] int int)
TheClass DataOutput, void writeLong(long)DataOutput
interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream. There is also a facility for converting aString
into Java modified UTF-8 format and writing the resulting series of bytes.For all the methods in this interface that write bytes it is generally true that if a byte cannot be written for any reason an
IOException
is thrown. @author Frank Yellin @version 1.13 0216 12/0203/0001 @see java.io.DataInput @see java.io.DataOutputStream @since JDK1.0
Writesanalong
value which is comprised offoureight bytes to the output stream. The byte values to be written in the order shown are:(byte)(0xff & (v >> 56)) (byte)(0xff & (v >> 48)) (byte)(0xff & (v >> 40)) (byte)(0xff & (v >> 32)) (byte)(0xff & (v >> 24)) (byte)(0xff & (v >> 16)) (byte)(0xff & (v >> 8)) (byte)(0xff & v)
The bytes written by this method may be read by the
readLong
method of interfaceDataInput
which will then return along
equal tov
. @param v thelong
value to be written. @exception IOException if an I/O error occurs.
A datainputoutput 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. @author unascribed @version 1.32340212/0203/0001 @see java.io.DataInputStream @since JDK1.0
Signals that an end of file or end of stream 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 whichtoansignal end of streamis an.unusualNotecondition.thatMostmany other inputstreamsoperations return a special value on end of stream. Note that some input operations react to end-of-file by returning a distinguished value (suchas -1)rather thanbythrowing an exception.@author Frank Yellin @version 1.
9 0211 12/0203/0001 @see java.io.DataInputStream @see java.io.IOException @since JDK1.0
Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances. The writeExternal and readExternal methods of the Externalizable interface are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. These methods supercede customized implementations of writeObject and readObject methods.
Object Serialization uses the Serializable and Externalizable interfaces. Object persistence mechanisms can use them as well. Each object to be stored is tested for the Externalizable interface. If the object supports Externalizable the writeExternal method is called. If the object does not support Externalizable and does implement Serializable the object is saved using ObjectOutputStream.
When an Externalizable object is reconstructed an instance is created using the public no-arg constructor then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.
An Externalizable instance can designate a substitution object via the writeReplace and readResolve methods documented in the Serializable interface.
@author unascribed @version 1.15 0216 12/0203/0001 @see java.io.ObjectOutputStream @see java.io.ObjectInputStream @see java.io.ObjectOutput @see java.io.ObjectInput @see java.io.Serializable @since JDK1.1
An abstract representation of file and directory pathnames.Class File, boolean canRead()User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract system-independent view of hierarchical pathnames. An abstract pathname has two components:
Each name in an abstract pathname except for the last denotes a directory; the last name may denote either a directory or a file. The empty abstract pathname has no prefix and an empty name sequence.
- An optional system-dependent prefix string
such as a disk-drive specifier"/"
for the UNIX root directory or"\\"
for a Win32 UNC pathname and- A sequence of zero or more string names.
The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property
file.separator
and is made available in the public static fields{@link #separator}
and{@link #separatorChar}
of this class. When a pathname string is converted into an abstract pathname the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.A pathname whether abstract or in string form may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname in contrast must be interpreted in terms of information taken from some other pathname. By default the classes in the
java.io
package always resolve relative pathnames against the current user directory. This directory is named by the system propertyuser.dir
and is typically the directory in which the Java virtual machine was invoked.The prefix concept is used to handle root directories on UNIX platforms and drive specifiers root directories and UNC pathnames on Win32 platforms as follows:
- For UNIX platforms the prefix of an absolute pathname is always
"/"
. Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix"/"
and an empty name sequence.- For Win32 platforms the prefix of a pathname that contains a drive specifier consists of the drive letter followed by
":"
and possibly followed by"\"
if the pathname is absolute. The prefix of a UNC pathname is"\\"
; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.Instances of the
File
class are immutable; that is once created the abstract pathname represented by aFile
object will never change. @version 1.98 03102 12/2203/01 @author unascribed @since JDK1.0
Tests whether the application can read the file denoted by this abstract pathname. @returnClass File, boolean canWrite()true
if and only if the file specified by this abstract pathname exists and can be read by the application;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Tests whether the application can modify to the file denoted by this abstract pathname. @returnClass File, boolean createNewFile()true
if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file;false
otherwise. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method denies write access to the file
Atomically creates a new empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. This method in combination with theClass File, File createTempFile(String, String){@link #deleteOnExit}
method can therefore serve as the basis for a simple but reliable cooperative file-locking protocol. @returntrue
if the named file does not exist and was successfully created;false
if the named file already exists @throws IOException If an I/O error occurred @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method denies write access to the file @since 1.2
Creates an empty file in the default temporary-file directory using the given prefix and suffix to generate its name. Invoking this method is equivalent to invokingClass File, File createTempFile(String, String, File){@link #createTempFile(java.lang.String java.lang.String java.io.File) createTempFile(prefix suffix null)}
. @param prefix The prefix string to be used in generating the file's name; must be at least three characters long @param suffix The suffix string to be used in generating the file's name; may benull
in which case the suffix".tmp"
will be used @return An abstract pathname denoting a newly-created empty file @throws IllegalArgumentException If theprefix
argument contains fewer than three characters @throws IOException If a file could not be created @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method does not allow a file to be created @since 1.2
Class File, boolean exists()Creates a new empty file in the specified directory using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically use the
- The file denoted by the returned abstract pathname did not exist before this method was invoked and
- Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
{@link #deleteOnExit}
method.The
prefix
argument must be at least three characters long. It is recommended that the prefix be a short meaningful string such as"hjb"
or"mail"
. Thesuffix
argument may benull
in which case the suffix".tmp"
will be used.To create the new file the prefix and the suffix may first be adjusted to fit the limitations of the underlying platform. If the prefix is too long then it will be truncated but its first three characters will always be preserved. If the suffix is too long then it too will be truncated but if it begins with a period character (
'.'
) then the period and the first three characters following it will always be preserved. Once these adjustments have been made the name of the new file will be generated by concatenating the prefix five or more internally-generated characters and the suffix.If the
directory
argument isnull
then the system-dependent default temporary-file directory will be used. The default temporary-file directory is specified by the system propertyjava.io.tmpdir
. On UNIX systems the default value of this property is typically"/tmp"
or"/var/tmp"
; on Win32 systems it is typically"c:\\temp"
. A different value may be given to this system property when the Java virtual machine is invoked but programmatic changes to this property are not guaranteed to have any effect upon the the temporary directory used by this method. @param prefix The prefix string to be used in generating the file's name; must be at least three characters long @param suffix The suffix string to be used in generating the file's name; may benull
in which case the suffix".tmp"
will be used @param directory The directory in which the file is to be created ornull
if the default temporary-file directory is to be used @return An abstract pathname denoting a newly-created empty file @throws IllegalArgumentException If theprefix
argument contains fewer than three characters @throws IOException If a file could not be created @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method does not allow a file to be created @since 1.2
Tests whether the file denoted by this abstract pathname exists. @returnClass File, File getAbsoluteFile()true
if and only if the file denoted by this abstract pathname exists;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Returns the absolute form of this abstract pathname. Equivalent to new File(this.{@link #getAbsolutePath}())
. @return The absolute abstract pathname denoting the same file or directory as this abstract pathname @throws SecurityException If a required system property value cannot be accessed. @since 1.2
Class File, String getAbsolutePath()Returns the absolute pathname string of this abstract pathname.Class File, File getCanonicalFile()If this abstract pathname is already absolute then the pathname string is simply returned as if by the
{@link #getPath}
method. If this abstract pathname is the empty abstract pathname then the pathname string of the current user directory which is named by the system propertyuser.dir
is returned. Otherwise this pathname is resolved in a system-dependent way. On UNIX systems a relative pathname is made absolute by resolving it against the current user directory. On Win32 systems a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname if any; if not it is resolved against the current user directory. @return The absolute pathname string denoting the same file or directory as this abstract pathname @throws SecurityException If a required system property value cannot be accessed. @see java.io.File#isAbsolute()
Returns the canonical form of this abstract pathname. Equivalent to new File(this.{@link #getCanonicalPath}())
. @return The canonical pathname string denoting the same file or directory as this abstract pathname @throws IOException If an I/O error occurs which is possible because the construction of the canonical pathname may require filesystem queries @throws SecurityException If a required system property value cannot be accessed. @since 1.2
Class File, String getCanonicalPath()Returns the canonical pathname string of this abstract pathname.Class File, boolean isDirectory()A canonical pathname is both absolute and unique. The precise definition of canonical form is system-dependent. This method first converts this pathname to absolute form if necessary as if by invoking the #getAbsolutePath method and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname resolving symbolic links (on UNIX platforms) and converting drive letters to a standard case (on Win32 platforms).
Every pathname that denotes an existing file or directory has a unique canonical form. Every pathname that denotes a nonexistent file or directory also has a unique canonical form. The canonical form of the pathname of a nonexistent file or directory may be different from the canonical form of the same pathname after the file or directory is created. Similarly the canonical form of the pathname of an existing file or directory may be different from the canonical form of the same pathname after the file or directory is deleted. @return The canonical pathname string denoting the same file or directory as this abstract pathname @throws IOException If an I/O error occurs which is possible because the construction of the canonical pathname may require filesystem queries @throws SecurityException If a required system property value cannot be accessed. @since JDK1.1
Tests whether the file denoted by this abstract pathname is a directory. @returnClass File, boolean isFile()true
if and only if the file denoted by this abstract pathname exists and is a directory;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and in addition satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. @returnClass File, boolean isHidden()true
if and only if the file denoted by this abstract pathname exists and is a normal file;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Tests whether the file named by this abstract pathname is a hidden file. The exact definition of hidden is system-dependent. On UNIX systems a file is considered to be hidden if its name begins with a period character (Class File, long lastModified()'.'
). On Win32 systems a file is considered to be hidden if it has been marked as such in the filesystem. @returntrue
if and only if the file denoted by this abstract pathname is hidden according to the conventions of the underlying platform @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file @since 1.2
Returns the time that the file denoted by this abstract pathname was last modified. @return AClass File, long length()long
value representing the time the file was last modified measured in milliseconds since the epoch (00:00:00 GMT January 1 1970) or0L
if the file does not exist or if an I/O error occurs @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. @return The length in bytes of the file denoted by this abstract pathname orClass File, String[] list()0L
if the file does not exist @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the file
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.Class File, String[] list(FilenameFilter)If this abstract pathname does not denote a directory then this method returns
null
. Otherwise an array of strings is returned one for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not in particular guaranteed to appear in alphabetical order. @return An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns
null
if this abstract pathname does not denote a directory or if an I/O error occurs. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the directory
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of theClass File, File[] listFiles(){@link #list()}
method except that the strings in the returned array must satisfy the filter. If the givenfilter
isnull
then all names are accepted. Otherwise a name satisfies the filter if and only if the valuetrue
results when the{@link FilenameFilter#accept}
method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes. @param filter A filename filter @return An array of strings naming the files and directories in the directory denoted by this abstract pathname that were accepted by the givenfilter
. The array will be empty if the directory is empty or if no names were accepted by the filter. Returnsnull
if this abstract pathname does not denote a directory or if an I/O error occurs. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the directory
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.Class File, File[] listFiles(FileFilter)If this abstract pathname does not denote a directory then this method returns
null
. Otherwise an array ofFile
objects is returned one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the{@link #File(java.io.File java.lang.String) File(File String)}
constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not in particular guaranteed to appear in alphabetical order. @return An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns
null
if this abstract pathname does not denote a directory or if an I/O error occurs. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the directory @since 1.2
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of theClass File, File[] listFiles(FilenameFilter){@link #listFiles()}
method except that the pathnames in the returned array must satisfy the filter. If the givenfilter
isnull
then all pathnames are accepted. Otherwise a pathname satisfies the filter if and only if the valuetrue
results when the{@link
method of the filter is invoked on the pathname. @param filter AFilenameFilterFileFilter#accept(java.io.File)}filenamefile filter @return An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returnsnull
if this abstract pathname does not denote a directory or if an I/O error occurs. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the directory @since 1.2
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of theClass File, File[] listRoots(){@link #listFiles()}
method except that the pathnames in the returned array must satisfy the filter. If the givenfilter
isnull
then all pathnames are accepted. Otherwise a pathname satisfies the filter if and only if the valuetrue
results when the{@link FilenameFilter#accept}
method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes. @param filter A filename filter @return An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returnsnull
if this abstract pathname does not denote a directory or if an I/O error occurs. @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to the directory @since 1.2
List the available filesystem roots.Class File, boolean mkdir()A particular Java platform may support zero or more hierarchically-organized file systems. Each file system has a
root
directory from which all other files in that file system can be reached. Windows platforms for example have a root directory for each active drive; UNIX platforms have a single root directory namely"/"
. The set of available filesystem roots is affected by various system-level operations such the insertion or ejection of removable media and the disconnecting or unmounting of physical or virtual disk drives.This method returns an array of
File
objects that denote the root directories of the available filesystem roots. It is guaranteed that the canonical pathname of any file physically present on the local machine will begin with one of the roots returned by this method.The canonical pathname of a file that resides on some other machine and is accessed via a remote-filesystem protocol such as SMB or NFS may or may not begin with one of the roots returned by this method. If the pathname of a remote file is syntactically indistinguishable from the pathname of a local file then it will begin with one of the roots returned by this method. Thus for example
File
objects denoting the root directories of the mapped network drives of a Windows platform will be returned by this method whileFile
objects containing UNC pathnames will not be returned by this method.Unlike most methods in this class this method does not throw security exceptions. If a security manager exists and its
{@link java.lang.SecurityManager#checkRead(java.lang.String)}
method denies read access to a particular root directory then that directory will not appear in the result. @return An array ofFile
objects denoting the available filesystem roots ornull
if the set of roots could not be determined. The array will be empty if there are no filesystem roots. @since 1.2
Creates the directory named by this abstract pathname. @returnClass File, boolean mkdirs()true
if and only if the directory was created;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method does not permit the named directory to be created
Creates the directory named by this abstract pathname including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories. @returnClass File, boolean renameTo(File)true
if and only if the directory was created along with all necessary parent directories;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method does not permit the named directory and all necessary parent directories and to be created
Renames the file denoted by this abstract pathname. @param dest The new abstract pathname for the named file @returnClass File, boolean setLastModified(long)true
if and only if the renaming succeeded;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method denies write access to either the old or new pathnames @throws NullPointerException If parameterdest
isnull
Sets the last-modified time of the file or directory named by this abstract pathname.Class File, boolean setReadOnly()All platforms support file-modification times to the nearest second but some provide more precision. The argument will be truncated to fit the supported precision. If the operation succeeds and no intervening operations on the file take place then the next invocation of the
{@link #lastModified}
method will return the (possibly truncated)time
argument that was passed to this method. @param time The new last-modified time measured in milliseconds since the epoch (00:00:00 GMT January 1 1970) @returntrue
if and only if the operation succeeded;false
otherwise @throws IllegalArgumentException If the argument is negative @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method denies write access to the named file @since 1.2
Marks the file or directory named by this abstract pathname so that only read operations are allowed. After invoking this method the file or directory is guaranteed not to change until it is either deleted or marked to allow write access. Whether or not a read-only file or directory may be deleted depends upon the underlying system. @returnClass File, URL toURL()true
if and only if the operation succeeded;false
otherwise @throws SecurityException If a security manager exists and its{@link java.lang.SecurityManager#checkWrite(java.lang.String)}
method denies write access to the named file @since 1.2
Converts this abstract pathname into afile:
URL. The exact form of the URL is system-dependent. If it can be determined that the file denoted by this abstract pathname is a directory then the resulting URL will end with a slash.Usage note: This method does not automatically escape characters that are illegal in URLs. It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI via the toURI method and then converting the URI into a URL via the URI.toURL method. @return
aA URL object representing the equivalent file URL.@throws MalformedURLExceptionifIf the path cannot be parsed as a URL @see #toURI() @see java.net.URI @see java.net.URI#toURL() @see java.net.URL @since 1.2
Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file an open socket or another source or sink of bytes. The main practical use for a file descriptor is to create aFileInputStream
orFileOutputStream
to contain it.Applications should not create their own file descriptors. @author Pavani Diwanji @version 1.
18 0219 12/0203/0001 @see java.io.FileInputStream @see java.io.FileOutputStream @since JDK1.0
AClass FileInputStream, void close()FileInputStream
obtains input bytes from a file in a file system. What files are available depends on the host environment.
FileInputStream
is meant for reading streams of raw bytes such as image data. For reading streams of characters consider usingFileReader
. @author Arthur van Hoff @version 1.45 0257 12/0203/0001 @see java.io.File @see java.io.FileDescriptor @see java.io.FileOutputStream @since JDK1.0
Closes this file input stream and releases any system resources associated with the stream.If this stream has an associated channel then the channel is closed as well. @exception IOException if an I/O error occurs. @revised 1.4 @spec JSR-51
Signals that an attempt to open the file denoted by a specified pathname has failed.This exception will be thrown by the FileInputStream FileOutputStream and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible for example when an attempt is made to open a read-only file for writing. @author unascribed @version 1.
20 0221 12/0203/0001 @since JDK1.0
A file output stream is an output stream for writing data to aClass FileOutputStream, constructor FileOutputStream(FileDescriptor)File
or to aFileDescriptor
. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms in particular allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.
FileOutputStream
is meant for writing streams of raw bytes such as image data. For writing streams of characters consider usingFileWriter
. @author Arthur van Hoff @version 1.39 0253 12/0203/0001 @see java.io.File @see java.io.FileDescriptor @see java.io.FileInputStream @since JDK1.0
Creates an output file stream to write to the specified file descriptor which represents an existing connection to an actual file in the file system.Class FileOutputStream, void close()First if there is a security manager its
checkWrite
method is called with the file descriptorfdObj
argument as its argument. @param fdObj the file descriptor to be opened for writing.@exception SecurityException if a security manager exists and itscheckWrite
method denies write access to the file descriptor.@see java.lang.SecurityManager#checkWrite(java.io.FileDescriptor)
Closes this file output stream and releases any system resources associated with this stream. This file output stream may no longer be used for writing bytes.If this stream has an associated channel then the channel is closed as well. @exception IOException if an I/O error occurs. @revised 1.4 @spec JSR-51
This class represents access to a file or directory. A FilePermission consists of a pathname and a set of actions valid for that pathname.Pathname is the pathname of the file or directory granted the specified actions. A pathname that ends in "/*" (where "/" is the file separator character
File.separatorChar
) indicates all the files and directories contained in that directory. A pathname that ends with "/-" indicates (recursively) all files and subdirectories contained in that directory. A pathname consisting of the special token "<<ALL FILES>>" matches any file.Note: A pathname consisting of a single "*" indicates all the files in the current directory while a pathname consisting of a single "-" indicates all the files in the current directory and (recursively) all files and subdirectories contained in the current directory.
The actions to be granted are passed to the constructor in a string containing a list of one or more comma-separated keywords. The possible keywords are "read" "write" "execute" and "delete". Their meaning is defined as follows:
- read
- read permission
- write
- write permission
- execute
- execute permission. Allows
Runtime.exec
to be called. Corresponds toSecurityManager.checkExec
.- delete
- delete permission. Allows
File.delete
to be called. Corresponds toSecurityManager.checkDelete
.The actions string is converted to lowercase before processing.
Be careful when granting FilePermissions. Think about the implications of granting read and especially write access to various files and directories. The "<<ALL FILES>>" permission with write action is especially dangerous. This grants permission to write to the entire file system. One thing this effectively allows is replacement of the system binary including the JVM runtime environment.
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so. @see java.security.Permission @see java.security.Permissions @see java.security.PermissionCollection @version 1.
67 0069 01/0212/0203 @author Marianne Mueller @author Roland Schemers @since 1.2 @serial exclude
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself construct an InputStreamReader on a FileInputStream.
FileReader
is meant for reading streams of characters. For reading streams of raw bytes consider using aFileInputStream
. @see InputStreamReader @see FileInputStream @version 1.10 0012 01/0212/0203 @author Mark Reinhold @since JDK1.1
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself construct an OutputStreamWriter on a FileOutputStream.Whether or not a file is available or may be created depends upon the underlying platform. Some platforms in particular allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.
@see OutputStreamWriter @see FileOutputStream @version 1.
FileWriter
is meant for writing streams of characters. For writing streams of raw bytes consider using aFileOutputStream
.11 0015 01/0212/0203 @author Mark Reinhold @since JDK1.1
Instances of classes that implement this interface are used to filter filenames. These instances are used to filter directory listings in thelist
method of classFile
and by the Abstract Window Toolkit's file dialog component. @author Arthur van Hoff @author Jonathan Payne @version 1.20 0221 12/0203/0001 @see java.awt.FileDialog#setFilenameFilter(java.io.FilenameFilter) @see java.io.File @see java.io.File#list(java.io.FilenameFilter) @since JDK1.0
AFilterInputStream
contains some other input stream which it uses as its basic source of data possibly transforming the data along the way or providing additional functionality. The classFilterInputStream
itself simply overrides all methods ofInputStream
with versions that pass all requests to the contained input stream. Subclasses ofFilterInputStream
may further override some of these methods and may also provide additional methods and fields. @author Jonathan Payne @version 1.23 0224 12/0203/0001 @since JDK1.0
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) which it uses as its basic sink of data but possibly transforming the data along the way or providing additional functionality.The class
FilterOutputStream
itself simply overrides all methods ofOutputStream
with versions that pass all requests to the underlying output stream. Subclasses ofFilterOutputStream
may further override some of these methods as well as provide additional methods and fields. @author Jonathan Payne @version 1.28 0229 12/0203/0001 @since JDK1.0
Abstract class for reading filtered character streams. The abstract classFilterReader
itself provides default methods that pass all requests to the contained stream. Subclasses ofFilterReader
should override some of these methods and may also provide additional methods and fields. @version 1.11 0013 01/0212/0203 @author Mark Reinhold @since JDK1.1
Abstract class for writing filtered character streams. The abstract classFilterWriter
itself provides default methods that pass all requests to the contained stream. Subclasses ofFilterWriter
should override some of these methods and may also provide additional methods and fields. @version 1.11 0013 01/0212/0203 @author Mark Reinhold @since JDK1.1
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations. @author unascribed @version 1.19 0220 12/0203/0001 @see java.io.InputStream @see java.io.OutputStream @since JDK1.0
This abstract class is the superclass of all classes representing an input stream of bytes.Class InputStream, boolean markSupported()Applications that need to define a subclass of
InputStream
must always provide a method that returns the next byte of input. @author Arthur van Hoff @version 1.36 0238 12/0203/0001 @see java.io.BufferedInputStream @see java.io.ByteArrayInputStream @see java.io.DataInputStream @see java.io.FilterInputStream @see java.io.InputStream#read() @see java.io.OutputStream @see java.io.PushbackInputStream @since JDK1.0
Tests if this input stream supports themark
andreset
methods. Whether or notmark
andreset
are supported is an invariant property of a particular input stream instance. ThemarkSupported
method ofInputStream
returnsfalse
. @returntrue
if thistrue typestream instance supports the mark and resetmethodmethods;false
otherwise. @see java.io.InputStream#mark(int) @see java.io.InputStream#reset()
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes andClass InputStreamReader, constructor InputStreamReader(InputStream)translatesdecodes them into charactersaccordingusingtoa specifiedcharacter encoding.charset
Theencodingcharset that it uses may be specified by name or may be given explicitly or the platform's defaultencodingcharset may be accepted.Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency consider wrapping an InputStreamReader within a BufferedReader. For example:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));@see BufferedReader @see InputStream @seeCharacter encodingsjava.nio.charset.Charset @version 1.25 0042 01/0212/0203 @author Mark Reinhold @since JDK1.1
Create an InputStreamReader that uses the defaultClass InputStreamReader, constructor InputStreamReader(InputStream, String)character encodingcharset. @param in An InputStream
Create an InputStreamReader that uses the namedClass InputStreamReader, String getEncoding()character encodingcharset. @param in An InputStream @paramenccharsetName The name of a supportedcharacter encodingcharset@exception UnsupportedEncodingException If the named
encodingcharset is not supported
Class InputStreamReader, int read(char[], int, int)ReturnsReturn thecanonicalname of the character encoding being used by this stream.If the encoding has an historical name then that name is returned; otherwise the encoding's canonical name is returned.
@returnIf this
InputStreamReaderinstance was created with the String) constructor then the returnedencodingname beingcanonicalunique for the encoding may differ from theencodingname passed to the constructor.MayThis method may returnnull
if the stream has been closed.a String representing the encoding nameThe historical name of this encoding or possiblynull
if the stream has been closed @seeCharacterjava.nio.charset.Charset @revised 1.4 @specencodingsJSR-51
Read characters into a portion of an array. @param cbuf Destination buffer @paramoffoffset Offset at which to start storing characters @paramlenlength Maximum number of characters to read @return The number of characters read or -1 if the end of the stream has been reached @exception IOException If an I/O error occurs
Signals that an I/O operation has been interrupted. AnInterruptedIOException
is thrown to indicate that an input or output transfer has been terminated because the thread performing it wasterminatedinterrupted. The field #bytesTransferred indicates how many bytes were successfully transferred before the interruption occurred. @author unascribed @version 1.15170212/0203/0001 @see java.io.InputStream @see java.io.OutputStream @see java.lang.Thread#interrupt() @since JDK1.0
Thrown when the Serialization runtime detects one of the following problems with a Class.@author unascribed @version 1.
- The serial version of the class does not match that of the class descriptor read from the stream
- The class contains unknown datatypes
- The class does not have an accessible no-arg constructor
17 0218 12/0203/0001 @since JDK1.1
Indicates that one or more deserialized objects failed validation tests. The argument should provide the reason for the failure. @see ObjectInputValidation @since JDK1.1 @author unascribed @version 1.12 0213 12/0203/0001 @since JDK1.1
This class is an input stream filter that provides the added functionality of keeping track of the current line number.A line is a sequence of bytes ending with a carriage return character (
'\r'
) a newline character ('\n'
) or a carriage return character followed immediately by a linefeed character. In all three cases the line terminating character(s) are returned as a single newline character.The line number begins at
0
and is incremented by1
when aread
returns a newline character. @author Arthur van Hoff @version 1.22 0223 12/0203/0001 @see java.io.LineNumberReader @since JDK1.0 @deprecated This class incorrectly assumes that bytes adequately represent characters. As of JDK 1.1 the preferred way to operate on character streams is via the new character-stream classes which include a class for counting line numbers.
A buffered character-input stream that keeps track of line numbers. This class defines methodsvoid setLineNumber(int)
andint getLineNumber()
for setting and getting the current line number respectively.By default line numbering begins at 0. This number increments as data is read and can be changed with a call to
setLineNumber(int)
. Note however thatsetLineNumber(int)
does not actually change the current position in the stream; it only changes the value that will be returned bygetLineNumber()
.A line is considered to be terminated by any one of a line feed ('\n') a carriage return ('\r') or a carriage return followed immediately by a linefeed. @version 1.
13 0015 01/0212/0203 @author Mark Reinhold @since JDK1.1
Thrown when serialization or deserialization is not active. @author unascribed @version 1.12 0213 12/0203/0001 @since JDK1.1
Thrown when an instance is required to have a Serializable interface. The serialization runtime or the class of the instance can throw this exception. The argument should be the name of the class. @author unascribed @version 1.11 0212 12/0203/0001 @since JDK1.1
ObjectInput extends the DataInput interface to include the reading of objects. DataInput includes methods for the input of primitive types ObjectInput extends that interface to include objects arrays and Strings. @author unascribed @version 1.16 0217 12/0203/0001 @see java.io.InputStream @see java.io.ObjectOutputStream @see java.io.ObjectInputStream @since JDK1.1
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.
ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.
Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.The method
readObject
is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type.Primitive data types can be read from the stream using the appropriate method on DataInput.
The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing which prevents existing objects from being overwritten.
Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's mostspecifiecspecific class.
For example to read from a stream as written by the example in ObjectOutputStream:
FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p = new ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); Date date = (Date)p.readObject(); istream.close();Classes control how they are serialized by implementing either the java.io.Serializable or java.io.Externalizable interfaces.
Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects saving and restoring entire graphs.
Serializable classes that require special handling during the serialization and deserialization process should implement
both ofthethesefollowing methods:
private void writeObject(java.io.ObjectOutputStream stream) throws IOException; private void readObject(java.io.ObjectInputStream stream) throws IOException ClassNotFoundException; private void readObjectNoData() throws ObjectStreamException;
The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput.
Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method then the end of default serialized data marks the end of the allotted data.
Primitive and object read calls issued from within a readExternal method behave in the same manner--if the stream is already positioned at the end of data written by the corresponding writeExternal method object reads will throw OptionalDataExceptions with eof set to true bytewise reads will return -1 and primitive reads will throw EOFExceptions. Note that this behavior does not hold for streams written with the old
ObjectStreamConstants.PROTOCOL_VERSION_1
protocol in which the end of data written by writeExternal methods is not demarcated and hence cannot be detected.The readObjectNoData method is responsible for initializing the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party and the receiver's version extends classes
that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream. Serialization does not read or assign values to the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public package or protected) or that there are get and set methods that can be used to restore the state.
Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface writeExternal and readExternal are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs. @author Mike Warres @author Roger Riggs @version 1.107 02136 01/0912/0103 @see java.io.DataInput @see java.io.ObjectOutputStream @see java.io.Serializable @see Object Serialization Specification Section 3 Object Input Classes @since JDK1.1
Get the value of the named Object field from the persistent field. @param name the name of the field @paramClass ObjectInputStream.GetField, boolean get(String, boolean)defvalueval the default value to use ifname
does not have a value @return the value of the namedObject
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named boolean field from the persistent field. @param name the name of the field @paramClass ObjectInputStream.GetField, byte get(String, byte)defvalueval the default value to use ifname
does not have a value @return the value of the namedboolean
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named byte field from the persistentClass ObjectInputStream.GetField, char get(String, char)fieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedbyte
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named char field from the persistentClass ObjectInputStream.GetField, double get(String, double)fieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedchar
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named double field from the persistent field. @param name the name of the field @paramClass ObjectInputStream.GetField, float get(String, float)defvalueval the default value to use ifname
does not have a value @return the value of the nameddouble
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named float field from the persistentClass ObjectInputStream.GetField, int get(String, int)fieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedfloat
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named int field from the persistentClass ObjectInputStream.GetField, long get(String, long)fieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedint
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named long field from the persistentClass ObjectInputStream.GetField, short get(String, short)fieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedlong
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Get the value of the named short field from the persistentfieldsfield. @param name the name of the field @paramdefvalueval the default value to use ifname
does not have a value @return the value of the namedshort
field @throws IOException if there are I/O errors while reading from the underlyingInputStream
@throws IllegalArgumentException if type ofname
is not serializable or if the field type is incorrect
Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.Class ObjectInputStream, constructor ObjectInputStream(InputStream)If there is a security manager installed this method first calls the security manager's
checkPermission
method with theSerializablePermission("enableSubclassImplementation")
permission to ensure it's ok to enable subclassing. @exception IOException Thrown if not called by a subclass. @throws SecurityException if a security manager exists and itscheckPermission
method denies enabling subclassing. @see SecurityManager#checkPermission @see java.io.SerializablePermission
Class ObjectInputStream, void close()CreateCreates an ObjectInputStream that reads from the specified InputStream.TheA serialization stream headercontaining the magic number and version number areis read from the stream and verified. Thismethodconstructor will block until the corresponding ObjectOutputStream has written and flushed the header.@paramIf
ina security manager is installed this constructor will check for theunderlying"enableSubclassImplementation"InputStreamSerializablePermissionfromwhen invoked directly or indirectly by the constructor of a subclass which overrides the ObjectInputStream.readFields or ObjectInputStream.readUnshared methods. @param in input stream to read from @exceptionthrows StreamCorruptedExceptionThe versionifor magic number arethe stream header is incorrect.@exceptionthrows IOExceptionAnif anexceptionI/Ooccurred in the underlyingerror occurs while reading stream.header @throws SecurityException if untrusted subclass illegally overrides security-sensitive methods @see ObjectInputStream#ObjectInputStream() @see ObjectInputStream#readFields() @see ObjectOutputStream#ObjectOutputStream(OutputStream)
Closes the input stream. Must be called to release any resources associated with the stream. @Class ObjectInputStream, void defaultReadObject()exceptionthrows IOException If an I/O error has occurred.
Read the non-static and non-transient fields of the current class from this stream. This may only be called from the readObject method of the class being deserialized. It will throw the NotActiveException if it is called otherwise. @Class ObjectInputStream, boolean enableResolveObject(boolean)exceptionthrowsjava.lang.ClassNotFoundException if the class of a serialized object could not be found. @exceptionthrows IOException if an I/O error occurs. @exceptionthrows NotActiveException if the stream is not currently reading objects.
Enable the stream to allow objects read from the stream to be replaced. When enabled the resolveObject method is called for every object being deserialized.Class ObjectInputStream, int read()If enable is true and there is a security manager installed this method first calls the security manager's
checkPermission
method with theSerializablePermission("enableSubstitution")
permission to ensure it's ok to enable the stream to allow objects read from the stream to be replaced. @param enable true for enabling use ofresolveObject
for every object being deserialized @return the previous setting before this method was invoked @throws SecurityException if a security manager exists and itscheckPermission
method denies enabling the stream to allow objects read from the stream to be replaced. @see SecurityManager#checkPermission @see java.io.SerializablePermission
Reads a byte of data. This method will block if no input is available. @return the byte read or -1 if the end of the stream is reached. @Class ObjectInputStream, int read(byte[], int, int)exceptionthrows IOException If an I/O error has occurred.
Reads into an array of bytes. This method will block until some input is available. Consider using java.io.DataInputStream.readFully to read exactly 'length' bytes. @paramClass ObjectInputStream, boolean readBoolean()bbuf the buffer into which the data is read @param off the start offset of the data @param len the maximum number of bytes read @return the actual number of bytes read -1 is returned when the end of the stream is reached. @exceptionthrows IOException If an I/O error has occurred. @see java.io.DataInputStream#readFully(byte[] int int)
Reads in a boolean. @return the boolean read. @Class ObjectInputStream, byte readByte()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads an 8 bit byte. @return the 8 bit byte read. @Class ObjectInputStream, char readChar()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads a 16 bit char. @return the 16 bit char read. @Class ObjectInputStream, ObjectStreamClass readClassDescriptor()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Read a class descriptor from the serialization stream. This method is called when the ObjectInputStream expects a class descriptor as the next item in the serialization stream. Subclasses of ObjectInputStream may override this method to read in class descriptors that have been written in non-standard formats (by subclasses of ObjectOutputStream which have overridden theClass ObjectInputStream, double readDouble()writeClassDescriptor
method). By default this method reads class descriptors according to the format defined in the Object Serialization specification.@return the class descriptor read @exceptionthrows IOException If an I/O error has occurred. @exceptionthrows ClassNotFoundException If the Class of a serialized object used in the class descriptor representation cannot be found @see java.io.ObjectOutputStream#writeClassDescriptor(java.io.ObjectStreamClass) @since 1.3
Reads a 64 bit double. @return the 64 bit double read. @Class ObjectInputStream, GetField readFields()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads the persistent fields from the stream and makes them available by name. @return theClass ObjectInputStream, float readFloat()GetField
object representing the persistent fields of the object being deserialized @exceptionthrowsjava.lang.ClassNotFoundException if the class of a serialized object could not be found. @exceptionthrows IOException if an I/O error occurs. @exceptionthrows NotActiveException if the stream is not currently reading objects. @since 1.2
Reads a 32 bit float. @return the 32 bit float read. @Class ObjectInputStream, void readFully(byte[])exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads bytes blocking until all bytes are read. @paramClass ObjectInputStream, void readFully(byte[], int, int)databuf the buffer into which the data is read @exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads bytes blocking until all bytes are read. @paramClass ObjectInputStream, int readInt()databuf the buffer into which the data is read @paramoffsetoff the start offset of the data @paramsizelen the maximum number of bytes to read @exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads a 32 bit int. @return the 32 bit integer read. @Class ObjectInputStream, long readLong()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads a 64 bit long. @return the read 64 bit long. @Class ObjectInputStream, Object readObject()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Read an object from the ObjectInputStream. The class of the object the signature of the class and the values of the non-transient and non-static fields of the class and all of its supertypes are read. Default deserializing for a class can be overriden using the writeObject and readObject methods. Objects referenced by this object are read transitively so that a complete equivalent graph of objects is reconstructed by readObject.Class ObjectInputStream, Object readObjectOverride()
The root object is completly restored when all of its fields and the objects it references are completely restored. At this point the object validation callbacks are executed in order based on their registered priorities. The callbacks are registered by objects (in the readObject special methods) as they are individually restored.Exceptions are thrown for problems with the InputStream and for classes that should not be deserialized. All exceptions are fatal to the InputStream and leave it in an indeterminate state; it is up to the caller to ignore or recover the stream state. @
exceptionthrowsjava.lang.ClassNotFoundException Class of a serialized object cannot be found. @exceptionthrows InvalidClassException Something is wrong with a class used by serialization. @exceptionthrows StreamCorruptedException Control information in the stream is inconsistent. @exceptionthrows OptionalDataException Primitive data was found in the stream instead of objects. @exceptionthrows IOException Any of the usual Input/Output related exceptions.
This method is called by trusted subclasses of ObjectOutputStream that constructed ObjectOutputStream using the protected no-arg constructor. The subclass is expected to provide an override method with the modifier "final". @return the Object read from the stream. @Class ObjectInputStream, short readShort()exceptionthrowsjava.lang.ClassNotFoundException Class definition of a serialized object cannot be found. @exceptionthrows OptionalDataException Primitive data was found in the stream instead of objects. @exceptionthrows IOException if I/O errors occurred while reading from the underlying stream @see #ObjectInputStream() @see #readObject() @since 1.2
Reads a 16 bit short. @return the 16 bit short read. @Class ObjectInputStream, int readUnsignedByte()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads an unsigned 8 bit byte. @return the 8 bit byte read. @Class ObjectInputStream, int readUnsignedShort()exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Reads an unsigned 16 bit short. @return the 16 bit short read. @Class ObjectInputStream, void registerValidation(ObjectInputValidation, int)exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Register an object to be validated before the graph is returned. While similar to resolveObject these validations are called after the entire graph has been reconstituted. Typically a readObject method will register the object with the stream so that when all of the objects are restored a final set of validations can be performed. @param obj the object to receive the validation callback. @param prio controls the order of callbacks;zero is a good default. Use higher numbers to be called back earlier lower numbers for later callbacks. Within a priority callbacks are processed in no particular order. @Class ObjectInputStream, Class resolveClass(ObjectStreamClass)exceptionthrows NotActiveException The stream is not currently reading objects so it is invalid to register a callback. @exceptionthrows InvalidObjectException The validation object is null.
Load the local class equivalent of the specified stream class description. Subclasses may implement this method to allow classes to be fetched from an alternate source.Class ObjectInputStream, Object resolveObject(Object)The corresponding method in ObjectOutputStream is annotateClass. This method will be invoked only once for each unique class in the stream. This method can be implemented by subclasses to use an alternate loading mechanism but must return a Class object. Once returned the serialVersionUID of the class is compared to the serialVersionUID of the serialized class. If there is a mismatch the deserialization fails and an exception is raised.
By default the class name is resolved relative to the class that called readObject.@paramvdesc an instance of class ObjectStreamClass @return a Class object corresponding tov
@exceptionthrows IOException Any of the usual Input/Output exceptions. @exceptionthrows ClassNotFoundException If class of a serialized object cannot be found.
This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization. Replacing objects is disabled until enableResolveObject is called. The enableResolveObject method checks that the stream requesting to resolve object can be trusted. Every reference to serializable objects is passed to resolveObject. To insure that the private state of objects is not unintentionally exposed only trusted streams may use resolveObject.Class ObjectInputStream, Class resolveProxyClass(String[])
This method is called after an object has been read but before it is returned from readObject. The default resolveObject method just returns the same object.
When a subclass is replacing objects it must insure that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.
This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object.@param obj object to be substituted @return the substituted object @exceptionthrows IOException Any of the usual Input/Output exceptions.
Returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the descriptors for dynamic proxy classes allowing them to use an alternate loading mechanism for the interfaces and the proxy class.Class ObjectInputStream, int skipBytes(int)This method is called exactly once for each unique proxy class descriptor in the stream.
The corresponding method in
ObjectOutputStream
isannotateProxyClass
. For a given subclass ofObjectInputStream
that overrides this method theannotateProxyClass
method in the corresponding subclass ofObjectOutputStream
must write any data or objects read by this method.The default implementation of this method in
ObjectInputStream
returns the result of callingProxy.getProxyClass
with the list ofClass
objects for the interfaces that are named in theinterfaces
parameter. TheClass
object for each interface namei
is the value returned by callingClass.forName(i false loader)whereloader
is that of the first non-null class loader up the execution stack ornull
if no non-null class loaders are on the stack (the same class loader choice used by theresolveClass
method).ThisUnless any of the resolved interfaces are non-public this same value ofloader
is also the class loader passed toProxy.getProxyClass
; if non-public interfaces are present their class loader is passed instead (if more than one non-public interface class loader is encountered anIllegalAccessError
is thrown). IfProxy.getProxyClass
throws anIllegalArgumentException
resolveProxyClass
will throw aClassNotFoundException
containing theIllegalArgumentException
. @param interfaces the list of interface names that were deserialized in the proxy class descriptor @return a proxy class for the specified interfaces @throws IOException any exception thrown by the underlyingInputStream
@throws ClassNotFoundException if the proxy class or any of the named interfaces could not be found @see ObjectOutputStream#annotateProxyClass(Class) @since 1.3
Skips bytes block until all bytes are skipped. @param len the number of bytes to be skipped @return the actual number of bytes skipped. @exceptionthrows EOFException If end of file is reached. @exceptionthrows IOException If other I/O error has occurred.
Callback interface to allow validation of objects within a graph. Allows an object to be called when a complete graph of objects has been deserialized. @author unascribed @version 1.15 0216 12/0203/0001 @see ObjectInputStream @see ObjectInputStream#registerValidation(java.io.ObjectInputValidation int) @since JDK1.1
ObjectOutput extends the DataOutput interface to include writing of objects. DataOutput includes methods for output of primitive types ObjectOutput extends that interface to include objects arrays and Strings. @author unascribed @version 1.13 0214 12/0203/0001 @see java.io.InputStream @see java.io.ObjectOutputStream @see java.io.ObjectInputStream @since JDK1.1
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream the objects can be reconsituted on another host or in another process.
Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class the values of the object's fields and arrays and the closure of any other objects referenced from the initial objects.
The method writeObject is used to write an object to the stream. Any object including Strings and arrays is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.
The default serialization mechanism for an object writes the class of the object the class signature and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
For example to write an object that can be read by the example in ObjectInputStream:
FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close();Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void readObject(java.io.ObjectInputStream stream) throws IOException ClassNotFoundException; private void writeObject(java.io.ObjectOutputStream stream) throws IOExceptionThe writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public package or protected) or that there are get and set methods that can be used to restore the state.
Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface writeExternal and readExternal are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Primitive data excluding serializable fields and externalizable data is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record.
(*)The blocking factor used for a block-data record will be 1024 bytes.(*)Each block-data record will be filled up to 1024 bytes or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject defaultWriteObject and writeFields initially terminate any existing block-data record. @author Mike Warres @author Roger Riggs @version 1.108 02130 01/0912/0103 @see java.io.DataOutput @see java.io.ObjectInputStream @see java.io.Serializable @see java.io.Externalizable @seeObject Serialization Specification Section 2 Object Output Classes @since JDK1.1
Put the value of the named Object field into the persistent field. @param name the name of the serializable field @paramClass ObjectOutputStream.PutField, void put(String, boolean)valueval the value to assign to the field
Put the value of the named boolean field into the persistent field. @param name the name of the serializable field @paramClass ObjectOutputStream.PutField, void put(String, byte)valueval the value to assign to the field
Put the value of the named byte field into the persistentClass ObjectOutputStream.PutField, void put(String, char)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Put the value of the named char field into the persistentClass ObjectOutputStream.PutField, void put(String, double)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Put the value of the named double field into the persistent field. @param name the name of the serializable field @paramClass ObjectOutputStream.PutField, void put(String, float)valueval the value to assign to the field
Put the value of the named float field into the persistentClass ObjectOutputStream.PutField, void put(String, int)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Put the value of the named int field into the persistentClass ObjectOutputStream.PutField, void put(String, long)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Put the value of the named long field into the persistentClass ObjectOutputStream.PutField, void put(String, short)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Put the value of the named short field into the persistentClass ObjectOutputStream.PutField, void write(ObjectOutput)fieldsfield. @param name the name of the serializable field @paramvalueval the value to assign to the field
Write the data and fields to the specified ObjectOutput stream. @param out the stream to write the data and fields to @throws IOException if I/O errors occur while writing to the underlying stream @deprecated This method does not write the values contained by thisPutField
object in a proper format and may result in corruption of the serialization stream. The correct way to writePutField
data is by calling the java.io.ObjectOutputStream#writeFields() method.
Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.Class ObjectOutputStream, constructor ObjectOutputStream(OutputStream)If there is a security manager installed this method first calls the security manager's
checkPermission
method with aSerializablePermission("enableSubclassImplementation")
permission to ensure it's ok to enable subclassing. @exception IOException Thrown if not called by a subclass. @throws SecurityException if a security manager exists and itscheckPermission
method denies enabling subclassing. @see SecurityManager#checkPermission @see java.io.SerializablePermission
Creates an ObjectOutputStream that writes to the specified OutputStream.Class ObjectOutputStream, void annotateClass(Class)The stream headerThis constructor writesisthe serialization streamwrittenheader to thestream.underlyingThestream;callercallers maywantwish tocallflush the stream immediatelysoto ensure thatthe correspondingconstructors forObjectInputStreamreceiving ObjectInputStreams willcan readnot block when reading the header.immediatelyIf a security manager is installed this constructor will check for the "enableSubclassImplementation" SerializablePermission when invoked directly or indirectly by the constructor of a subclass which overrides the ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared methods. @param out
OutputStreamoutput stream toread fromwrite to @exceptionthrows IOExceptionAny exceptionif anthrownI/Oby the underlyingerror occurs whileOutputStream.writing stream header @throws SecurityException if untrusted subclass illegally overrides security-sensitive methods @see ObjectOutputStream#ObjectOutputStream() @see ObjectOutputStream#putFields() @see ObjectInputStream#ObjectInputStream(InputStream)
Subclasses may implement this method to allow class data to be stored in the stream. By default this method does nothing. The corresponding method in ObjectInputStream is resolveClass. This method is called exactly once for each unique class in the stream. The class name and signature will have already been written to the stream. This method may make free use of the ObjectOutputStream to save any representation of the class it deems suitable (for example the bytes of the class file). The resolveClass method in the corresponding subclass of ObjectInputStream must read and use any data or objects written by annotateClass. @param cl the class to annotate custom data for @Class ObjectOutputStream, void close()exceptionthrows IOException Any exception thrown by the underlying OutputStream.
Closes the stream. This method must be called to release any resources associated with the stream. @Class ObjectOutputStream, void drain()exceptionthrows IOException If an I/O error has occurred.
Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to theClass ObjectOutputStream, boolean enableReplaceObject(boolean)underlayingunderlying stream. @throws IOException if I/O errors occur while writing to the underlying stream
Enable the stream to do replacement of objects in the stream. When enabled the replaceObject method is called for every object being serialized.Class ObjectOutputStream, void flush()If
enable
is true and there is a security manager installed this method first calls the security manager'scheckPermission
method with aSerializablePermission("enableSubstitution")
permission to ensure it's ok to enable the stream to do replacement of objects in the stream. @param enable boolean parameter to enable replacement of objects @return the previous setting before this method was invoked @throws SecurityException if a security manager exists and itscheckPermission
method denies enabling the stream to do replacement of objects in the stream. @see SecurityManager#checkPermission @see java.io.SerializablePermission
Flushes the stream. This will write any buffered output bytes and flush through to the underlying stream. @Class ObjectOutputStream, PutField putFields()exceptionthrows IOException If an I/O error has occurred.
Retrieve the object used to buffer persistent fields to be written to the stream. The fields will be written to the stream when writeFields method is called. @return an instance of the class Putfield that holds the serializable fields @Class ObjectOutputStream, Object replaceObject(Object)exceptionthrows IOException if I/O errors occur @since 1.2
This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization. Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacment can be trusted. The first occurrence of each object written into the serialization stream is passed to replaceObject. Subsequent references to the object are replaced by the object returned by the original call to replaceObject. To ensure that the private state of objects is not unintentionally exposed only trusted streams may use replaceObject.Class ObjectOutputStream, void useProtocolVersion(int)
The ObjectOutputStream.writeObject method takes a parameter of type Object (as opposed to type Serializable) to allow for cases where non-serializable objects are replaced by serializable ones.When a subclass is replacing objects it must insure that either a complementary substitution must be made during deserialization or that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.
This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object. This method should return the object to be substituted or the original object.Null can be returned as the object to be substituted but may cause NullReferenceException in classes that contain references to the original object since they may be expecting an object instead of null. @param obj the object to be replaced @return the alternate object that replaced the specified one @
exceptionthrows IOException Any exception thrown by the underlying OutputStream.
Specify stream protocol version to use when writing the stream.Class ObjectOutputStream, void write(byte[])This routine provides a hook to enable the current version of Serialization to write in a format that is backwards compatible to a previous version of the stream format.
Every effort will be made to avoid introducing additional backwards incompatibilities; however sometimes there is no other alternative. @param version use ProtocolVersion from java.io.ObjectStreamConstants. @
exceptionthrows IllegalStateExceptionThrownif called after any objects have been serialized. @exceptionthrows IllegalArgumentException if invalid version is passed in. @throws IOException if I/O errors occur @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1 @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_2 @since 1.2
Writes an array of bytes. This method will block until the bytes are actually written. @paramClass ObjectOutputStream, void write(byte[], int, int)bbuf the data to be written @exceptionthrows IOException If an I/O error has occurred.
Writes a sub array of bytes. @paramClass ObjectOutputStream, void write(int)bbuf the data to be written @param off the start offset in the data @param len the number of bytes that are written @exceptionthrows IOException If an I/O error has occurred.
Writes a byte. This method will block until the byte is actually written. @paramClass ObjectOutputStream, void writeBoolean(boolean)dataval the byte to be written to the stream @exceptionthrows IOException If an I/O error has occurred.
Writes a boolean. @paramClass ObjectOutputStream, void writeByte(int)dataval the boolean to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes an 8 bit byte. @paramClass ObjectOutputStream, void writeBytes(String)dataval the byte value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a String as a sequence of bytes. @paramClass ObjectOutputStream, void writeChar(int)datastr the String of bytes to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a 16 bit char. @paramClass ObjectOutputStream, void writeChars(String)dataval the char value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a String as a sequence of chars. @paramClass ObjectOutputStream, void writeClassDescriptor(ObjectStreamClass)datastr the String of chars to be written @throws IOException if I/O errors occur while writing to the underlying stream
Write the specified class descriptor to the ObjectOutputStream. Class descriptors are used to identify the classes of objects written to the stream. Subclasses of ObjectOutputStream may override this method to customize the way in which class descriptors are written to the serialization stream. The corresponding method in ObjectInputStreamClass ObjectOutputStream, void writeDouble(double)readClassDescriptor
should then be overridden to reconstitute the class descriptor from its custom stream representation. By default this method writes class descriptors according to the format defined in the Object Serialization specification.
Note that this method will only be called if the ObjectOutputStream is not using the old serialization stream format (set by calling ObjectOutputStream'suseProtocolVersion
method). If this serialization stream is using the old format (PROTOCOL_VERSION_1
) the class descriptor will be written internally in a manner that cannot be overridden or customized.@paramclassdescdesc class descriptor to write to the stream @exceptionthrows IOException If an I/O error has occurred. @see java.io.ObjectInputStream#readClassDescriptor() @see #useProtocolVersion(int) @see java.io.ObjectStreamConstants#PROTOCOL_VERSION_1 @since 1.3
Writes a 64 bit double. @paramClass ObjectOutputStream, void writeFloat(float)dataval the double value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a 32 bit float. @paramClass ObjectOutputStream, void writeInt(int)dataval the float value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a 32 bit int. @paramClass ObjectOutputStream, void writeLong(long)dataval the integer value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Writes a 64 bit long. @paramClass ObjectOutputStream, void writeObject(Object)dataval the long value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Write the specified object to the ObjectOutputStream. The class of the object the signature of the class and the values of the non-transient and non-static fields of the class and all of its supertypes are written. Default serialization for a class can be overridden using the writeObject and the readObject methods. Objects referenced by this object are written transitively so that a complete equivalent graph of objects can be reconstructed by an ObjectInputStream.Class ObjectOutputStream, void writeShort(int)
Exceptions are thrown for problems with the OutputStream and for classes that should not be serialized. All exceptions are fatal to the OutputStream which is left in an indeterminate state and it is up to the caller to ignore or recover the stream state. @exceptionthrows InvalidClassException Something is wrong with a class used by serialization. @exceptionthrows NotSerializableException Some object to be serialized does not implement the java.io.Serializable interface. @exceptionthrows IOException Any exception thrown by the underlying OutputStream.
Writes a 16 bit short. @paramClass ObjectOutputStream, void writeUTF(String)dataval the short value to be written @throws IOException if I/O errors occur while writing to the underlying stream
Primitive data write of this String in UTF format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream. @paramsstr the String in UTF format @throws IOException if I/O errors occur while writing to the underlying stream
Serialization's descriptor for classes. It contains the name and serialVersionUID of the class.Class ObjectStreamClass, ObjectStreamField[] NO_FIELDSThe ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method.The algorithm to compute the SerialVersionUID is described in
Object Serialization Specification Section 4.4 Stream Unique Identifiers. @author Mike Warres @author Roger Riggs @version 1.98 02/02/00 @see ObjectStreamField @seeObject Serialization Specification Section 4 Class Descriptors @since JDK1.1
SetserialPersistentFieldsof a Serializable class to thisvalueto denote that the class hasindicating noSerializableserializable fields.
Constants written into the Object Serialization Stream. @author unascribed @version 1.29 0230 12/0203/0001 @since JDK 1.1
Superclass of all exceptions specific to Object Stream classes. @author unascribed @version 1.10 0211 12/0203/0001 @since JDK1.1
A description of a Serializable field from a Serializable class. An array of ObjectStreamFields is used to declare the Serializable fields of a class. @author Mike Warres @author Roger Riggs @version 1.Class ObjectStreamField, constructor ObjectStreamField(String, Class)30 0239 01/0212/0003 @see ObjectStreamClass @since 1.2
Create a Serializable field with the specified type. This field should be documented with aserialField
tag. @paramnname the name of the serializable field @paramclazztype theClass
object of the serializable field
UnexpectedException indicating the failure of an object read operation due to unread primitive data or the end of dataappearedbelonging to a serialized object inanthe stream. This exception may beObjectInputStreamthrowntryingin two cases:attempt was made to read an
- An
Object. Occursobject when the next element in the streamcontainsis primitive data.instead ofIn this case theobjectOptionalDataException'sthatlength field isexpected byset toreadObject.the numberThe EOF flagof bytes ofinprimitive data immediately readable from theexceptionstream and the eof field istruesetindicatingto false.thatAn no moreattempt wasprimitivemade to read past the end of dataisconsumable by a class-definedavailablereadObject or readExternal method.TheIn this case the OptionalDataException'scounteof fieldcontainsis set to true and thenumber of bytes availablelength field is set toread0. @author unascribed @version%I% %G%1.15 12/03/01 @since JDK1.1
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 some sink.Applications that need to define a subclass of
OutputStream
must always provide at least a method that writes one byte of output. @author Arthur van Hoff @version 1.23 0224 12/0203/0001 @see java.io.BufferedOutputStream @see java.io.ByteArrayOutputStream @see java.io.DataOutputStream @see java.io.FilterOutputStream @see java.io.InputStream @see java.io.OutputStream#write(int) @since JDK1.0
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it areClass OutputStreamWriter, constructor OutputStreamWriter(OutputStream, String)translatedencoded into bytesaccordingusingtoa specifiedcharacter encoding.charset
Theencodingcharset that it uses may be specified by name or may be given explicitly or the platform's defaultencodingcharset may be accepted.Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.
For top efficiency consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:
Writer out = new BufferedWriter(new OutputStreamWriter(System.out));A surrogate pair is a character represented by a sequence of two char values: A high surrogate in the range '\uD800' to '\uDBFF' followed by a low surrogate in the range '\uDC00' to '\uDFFF'. If the character represented by a surrogate pair cannot be encoded by a given charset then a charset-dependent substitution sequence is written to the output stream.
A malformed surrogate element is a high surrogate that is not followed by a low surrogate or a low surrogate that is not preceeded by a high surrogate. It is illegal to attempt to write a character stream containing malformed surrogate elements. The behavior of an instance of this class when a malformed surrogate element is written is not specified.
@see BufferedWriter @see OutputStream @seeCharacter encodingsjava.nio.charset.Charset @version 1.28 0243 01/0212/0003 @author Mark Reinhold @since JDK1.1
Create an OutputStreamWriter that uses the namedClass OutputStreamWriter, String getEncoding()character encodingcharset. @param out An OutputStream @paramenccharsetName The name of a supportedcharacter encodingcharset@exception UnsupportedEncodingException If the named encoding is not supported
ReturnsReturn thecanonicalname of the character encoding being used by this stream.If the encoding has an historical name then that name is returned; otherwise the encoding's canonical name is returned.
@returnIf this
OutputStreamWriterinstance was created with the String) constructor then the returnedencodingname beingcanonicalunique for the encoding may differ from theencodingname passed to the constructor.MayThis method may return null if the stream has been closed.a String representing the encoding nameThe historical name of this encoding or possiblynull
if the stream has been closed @seeCharacterjava.nio.charset.Charset @revised 1.4 @specencodingsJSR-51
A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream. Typically data is read from aPipedInputStream
object by one thread and data is written to the correspondingPipedOutputStream
by some other thread. Attempting to use both objects from a single thread is not recommended as it may deadlock the thread. The piped input stream contains a buffer decoupling read operations from write operations within limits. @author James Gosling @version 1.30 0231 12/0203/0001 @see java.io.PipedOutputStream @since JDK1.0
A piped output stream can be connected to a piped input stream to create a communications pipe. The piped output stream is the sending end of the pipe. Typically data is written to aPipedOutputStream
object by one thread and data is read from the connectedPipedInputStream
by some other thread. Attempting to use both objects from a single thread is not recommended as it may deadlock the thread. @author James Gosling @version 1.23 0224 12/0203/0001 @see java.io.PipedInputStream @since JDK1.0
Piped character-input streams. @version 1.12 0013 01/0212/0203 @author Mark Reinhold @since JDK1.1
Piped character-output streams. @version 1.13 0014 01/0212/0203 @author Mark Reinhold @since JDK1.1
APrintStream
adds functionality to another output stream namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams aPrintStream
never throws anIOException
; instead exceptional situations merely set an internal flag that can be tested via thecheckError
method. Optionally aPrintStream
can be created so as to flush automatically; this means that theflush
method is automatically invoked after a byte array is written one of theprintln
methods is invoked or a newline character or byte ('\n'
) is written.All characters printed by a
PrintStream
are converted into bytes using the platform's default character encoding. The{@link PrintWriter}
class should be used in situations that require writing characters rather than bytes. @version 1.21 0024 01/0212/0203 @author Frank Yellin @author Mark Reinhold @since JDK1.0
Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes for which a program should use unencoded byte streams.Class PrintWriter, boolean checkError()Unlike the PrintStream class if automatic flushing is enabled it will be done only when one of the println() methods is invoked rather than whenever a newline character happens to be output. The println() methods use the platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError(). @version 1.
24 0228 12/0203/0001 @author Frank Yellin @author Mark Reinhold @since JDK1.1
Flush the stream if it's not closed and check its error state. Errors are cumulative; once the stream encounters an error this routine will return true on all successive calls. @return True if the print stream has encountered an error either on the underlying output stream or during a format conversion.Class PrintWriter, void close()
Close the stream. @see #checkError()Class PrintWriter, void flush()
Flush the stream. @see #checkError()Class PrintWriter, void write(String)
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions. @param s String to be writtenClass PrintWriter, void write(String, int, int)
Write a portion of a string. @param s A String @param off Offset from which to start writing characters @param len Number of characters to writeClass PrintWriter, void write(char[])
Write an array of characters. This method cannot be inherited from the Writer class because it must suppress I/O exceptions. @param buf Array of characters to be writtenClass PrintWriter, void write(char[], int, int)
Write a portion of an array of characters. @param buf Array of characters @param off Offset from which to start writing characters @param len Number of characters to writeClass PrintWriter, void write(int)
Write a single character. @param c int specifying a character to be written.
APushbackInputStream
adds functionality to another input stream namely the ability to "push back" or "unread" one byte. This is useful in situations where it is convenient for a fragment of code to read an indefinite number of data bytes that are delimited by a particular byte value; after reading the terminating byte the code fragment can "unread" it so that the next read operation on the input stream will reread the byte that was pushed back. For example bytes representing the characters constituting an identifier might be terminated by a byte representing an operator character; a method whose job is to read just an identifier can read until it sees the operator and then push the operator back to be re-read. @author David Connelly @author Jonathan Payne @version 1.31 0232 12/0203/0001 @since JDK1.0
A character-stream reader that allows characters to be pushed back into the stream. @version 1.14 0015 01/0212/0203 @author Mark Reinhold @since JDK1.1
Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor or index into the implied array called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended. The file pointer can be read by theClass RandomAccessFile, constructor RandomAccessFile(File, String)getFilePointer
method and set by theseek
method.It is generally true of all the reading routines in this class that if end-of-file is reached before the desired number of bytes has been read an
EOFException
(which is a kind ofIOException
) is thrown. If any byte cannot be read for any reason other than end-of-file anIOException
other thanEOFException
is thrown. In particular anIOException
may be thrown if the stream has been closed. @author unascribed @version 1.56 0267 12/0203/0001 @since JDK1.0
Creates a random access file stream to read from and optionally to write to the file specified by the File argument. A new FileDescriptor object is created to represent this file connection.Class RandomAccessFile, constructor RandomAccessFile(String, String)The mode argument
must either bespecifies the accessequalmode in which the file is to be opened. The permitted values and their meanings are:The
"r" orOpen for reading only. Invoking any of the write methods of the resulting object will cause an java.io.IOException to be thrown. "rw" indicatingthatOpen for reading and writing. If the fileisdoestonot already exist then an attempt will beopenedmade to create it."rws" Open for inputreadingonlyand writing as with "rw" and also require that every update to the file's content or metadata be written synchronously to the underlying storage device."rwd" Open for bothreading and writing asinputwith "rw" andoutputalso requirerespectivelythat every update to the file's content be written synchronously to the underlying storage device.write"rws"methodsandon"rwd"this objectmodes workwillmuch like the force(boolean) method of the java.nio.channels.FileChannel class passing arguments of true and false respectively except that they alwaysthrow anapply toIOExceptioneveryifI/O operation and are therefore often more efficient. If the fileis openedresides onwitha local storage device then when an invocation of amodemethod of"r".thisIfclass returns it is guaranteed that all changes made to themodefile by that invocation will have been written to that device. This is"rw"usefulandfor ensuring that critical information is not lost in the event of a system crash. If the file does notexistreside on a local device thenan attemptno such guarantee is made.The "rwd" mode
can be used tocreatereduceitthe number of I/O operations performed.AnUsingIOException"rwd"is thrownonly requiresifupdates to the file'sargumentcontent to bereferswritten toastorage;directoryusing "rws" requires updates to both the file's content and its metadata to be written which generally requires at least one more low-level I/O operation.If there is a security manager its
checkRead
method is called with the pathname of thefile
argument as its argument to see if read access to the file is allowed. If the modeisallows"rw"writing the security manager'scheckWrite
method is also called with the path argument to see if write access to the file is allowed. @param file the file object.@param mode the access mode.as described above @exception IllegalArgumentException if the mode argument is not equal to one of "r"or"rw"to"rws" or "rwrwd".@exception FileNotFoundException if the file exists but is a directory rather than a regular file or cannot be opened or created for any other reason @exception SecurityException if a security manager exists and itscheckRead
method denies read access to the file or the mode is "rw" and the security manager'scheckWrite
method denies write access to the file.@see java.iolang.FileSecurityManager#getPathcheckRead(java.lang.String) @see java.lang.SecurityManager#checkReadcheckWrite(java.lang.String) @see java.langnio.SecurityManagerchannels.FileChannel#checkWriteforce(java.lang.Stringboolean) @revised 1.4 @spec JSR-51
Creates a random access file stream to read from and optionally to write to a file with the specified name. A new FileDescriptor object is created to represent the connection to the file.Class RandomAccessFile, void close()The mode argument
mustspecifieseither be equal to "r"theoraccess"rw"modeindicating thatwith which the file is to be openedfor input only or for both input and output respectively. Thewrite methods on this object will always throw an IOException if the file is opened with a mode of "r". If the mode ispermitted"rw"values andthe file does not exist then an attempt is made to createtheirit. AnmeaningsIOExceptionareis thrown ifas specified for thename argument refers toRandomAccessFile(FileaString)directoryconstructor.If there is a security manager its
checkRead
method is called with thename
argument as its argument to see if read access to the file is allowed. If the modeisallows"rw"writing the security manager'scheckWrite
method is also called with thename
argument as its argument to see if write access to the file is allowed. @param name the system-dependent filename.@param mode the access mode.@exception IllegalArgumentException if the mode argument is not equal to one of "r"or"rw"to"rws" or "rwrwd".@exception FileNotFoundException if the file exists but is a directory rather than a regular file or cannot be opened or created for any other reason @exception SecurityException if a security manager exists and itscheckRead
method denies read access to the file or the mode is "rw" and the security manager'scheckWrite
method denies write access to the file.@see java.lang.SecurityException @see java.lang.SecurityManager#checkRead(java.lang.String) @see java.lang.SecurityManager#checkWrite(java.lang.String) @revised 1.4 @spec JSR-51
Closes this random access file stream and releases any system resources associated with the stream. A closed random access file cannot perform input or output operations and cannot be reopened.Class RandomAccessFile, FileDescriptor getFD()If this file has an associated channel then the channel is closed as well. @exception IOException if an I/O error occurs. @revised 1.4 @spec JSR-51
Returns the opaque file descriptor object associated with this stream. @return the file descriptor object associated with this stream. @exception IOException if an I/O error occurs. @see java.io.FileDescriptor
Abstract class for reading character streams. The only methods that a subclass must implement are read(char[] int int) and close(). Most subclasses however will override some of the methods defined here in order to provide higher efficiency additional functionality or both. @see BufferedReader @see LineNumberReader @see CharArrayReader @see InputStreamReader @see FileReader @see FilterReader @see PushbackReader @see PipedReader @see StringReader @see Writer @version 1.Class Reader, int read(char[])21 0023 01/0212/0203 @author Mark Reinhold @since JDK1.1
Read characters into an array. This method will block until some input is available an I/O error occurs or the end of the stream is reached. @param cbuf Destination buffer @return The number ofbytescharacters read or -1 if the end of the stream has been reached @exception IOException If an I/O error occurs
ASequenceInputStream
represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached whereupon it reads from the second one and so on until end of file is reached on the last of the contained input streams. @author Author van Hoff @version 1.23 0224 12/0203/0001 @since JDK1.0
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.To allow subtypes of non-serializable classes to be serialized the subtype may assume responsibility for saving and restoring the state of the supertype's public protected and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable
inif this is not the case. The error will be detected at runtime.During deserialization the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.
When traversing a graph an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException ClassNotFoundException;The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object's fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
Serializable classes that need to designate an alternative object to be used when writing an object to the stream should implement this special method with the exact signature:
ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;This writeReplace method is invoked by serialization if the method exists and it would be accessible from a method defined within the class of the object being serialized. Thus the method can have private protected and package-private access. Subclass access to this method follows java accessibility rules.
Classes that need to designate a replacement when an instance of it is read from the stream should implement this special method with the exact
signatutesignature.
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;This readResolve method follows the same invocation rules and accessibility rules as writeReplace. @author unascribed @version 1.
16190212/0203/0001 @see java.io.ObjectOutputStream @see java.io.ObjectInputStream @see java.io.ObjectOutput @see java.io.ObjectInput @see java.io.Externalizable @since JDK1.1
This class is for Serializable permissions. A SerializablePermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.The target name is the name of the Serializable permission (see below).
The following table lists all the possible SerializablePermission target names and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.
@see java.security.BasicPermission @see java.security.Permission @see java.security.Permissions @see java.security.PermissionCollection @see java.lang.SecurityManager @version 1.
Permission Target Name What the Permission Allows Risks of Allowing this Permission enableSubclassImplementation Subclass implementation of ObjectOutputStream or ObjectInputStream to override the default serialization or deserialization respectively of objects Code can use this to serialize or deserialize classes in a purposefully malfeasant manner. For example during serialization malicious code can use this to purposefully store confidential private field data in a way easily accessible to attackers. Or during deserializaiton it could for example deserialize a class with all its private fields zeroed out. enableSubstitution Substitution of one object for another during serialization or deserialization This is dangerous because malicious code can replace the actual object with one which has incorrect or malignant data. 13 0214 12/0203/0001 @author Joe Fialli @since 1.2
Thrown when control information that was read from an object stream violates internal consistency checks. @author unascribed @version 1.11 0212 12/0203/0001 @since JDK1.1
TheStreamTokenizer
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: white space alphabetic numeric string quote and comment character. Each character can have zero or more of these attributes.In addition an instance has four flags. These flags indicate:
- Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens.
- Whether C-style comments are to be recognized and skipped.
- Whether C++-style comments are to be recognized and skipped.
- Whether the characters of identifiers are converted to lowercase.
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 valueTT_EOF
. @author James Gosling @version 1.36 0237 12/0203/0001 @see java.io.StreamTokenizer#nextToken() @see java.io.StreamTokenizer#TT_EOF @since JDK1.0
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 aByteArrayInputStream
.Only the low eight bits of each character in the string are used by this class. @author Arthur van Hoff @version 1.
22 0223 12/0203/0001 @see java.io.ByteArrayInputStream @see java.io.StringReader @since JDK1.0 @deprecated This class does not properly convert characters into bytes. As of JDK 1.1 the preferred way to create a stream from a string is via theStringReader
class.
A character stream whose source is a string. @version 1.15 0016 01/0212/0203 @author Mark Reinhold @since JDK1.1
A character stream that collects its output in a string buffer which can then be used to construct a string.Class StringWriter, void close()Closing a StringWriter has no effect. The methods in this class can be called after the stream has been closed without generating an IOException. @version 1.
18 0020 01/0212/0203 @author Mark Reinhold @since JDK1.1
Close theClosing astreamStringWriter has no effect.ThisThe methodsmethod does not releasein this class can be called after thebuffer since its contents might still bestream has been closed without generating anrequiredIOException.
Signals that a sync operation has failed. @author Ken Arnold @version 1.12 0213 12/0203/0001 @see java.io.FileDescriptor#sync @see java.io.IOException @since JDK1.1
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. See thewriteUTF
method for the format in which UTF-8 strings are read and written. @author Frank Yellin @version 1.9 0210 12/0203/0001 @see java.io.DataInput @see java.io.DataInputStream#readUTF(java.io.DataInput) @see java.io.IOException @since JDK1.0
The Character Encoding is not supported. @author Asmus Freytag @version 1.13 0214 12/0203/0001 @since JDK1.1
Signals that one of the ObjectStreamExceptions was thrown during a write operation. Thrown during a read operation when one of the ObjectStreamExceptions was thrown during a write operation. The exception that terminated the write can be found in the detail field. The stream is reset to it's initial state and all references to objects already deserialized are discarded.Class WriteAbortedException, constructor WriteAbortedException(String, Exception)As of release 1.4 this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "exception causing the abort" that is provided at construction time and accessed via the public #detail field is now known as the cause and may be accessed via the Throwable#getCause() method as well as the aforementioned "legacy field."
@author unascribed @version 1.12 0216 12/0203/0001 @since JDK1.1
Class WriteAbortedException, Exception detailThrownConstructsduringaread operation when one of the ObjectStreamExceptions was thrownWriteAbortedExceptionduringwith awritestringoperation.describingThethe exceptionthatandterminatedthewrite can be foundexceptionincausing thedetail field. The stream is reset to it's initial state andd all references to objects already deserialized are discardedabort. @param s String describing the exception. @param ex Exception causing the abort.
Exception that was caught while writing the ObjectStream.This field predates the general-purpose exception chaining facility. The Throwable#getCause() method is now the preferred means of obtaining this information. @serial
Abstract class for writing to character streams. The only methods that a subclass must implement are write(char[] int int) flush() and close(). Most subclasses however will override some of the methods defined here in order to provide higher efficiency additional functionality or both. @see Writer @see BufferedWriter @see CharArrayWriter @see FilterWriter @see OutputStreamWriter @see FileWriter @see PipedWriter @see PrintWriter @see StringWriter @see Reader @version 1.19 0020 01/0212/0203 @author Mark Reinhold @since JDK1.1