Java I/O class library design is quite rich, in our usual programming also often contact, often most of the system has a number of IO operation of the package code, usually used to turn over the API or to find a good way to copy to get it done, This brings the Java itself to provide these methods are unfamiliar, usually do not comb, the Java IO package below these common classes are more messy. So here through the API documentation and java.io below the source to sort under.
1. Superclass of all classes representing byte input and output streams (inputstream/outputstream)
Construction Method:
InputStream () create an input stream stream
Method:
int available (): Returns the estimated number of bytes that a method call can read (or skip) from this input stream without blocking.
void Close (): closes this input stream and frees all system resources associated with the stream.
abstract int Read (): reads the next byte of data from the input stream.
int read (byte[] b): Reads a certain number of bytes from the input stream and stores it in buffer array B.
int read (byte[] b, int off, int len): reads up to len data bytes in the input stream into a byte array.
Long N: Skips and discards the N bytes of data in this input stream.
Boolean mark (int readlimit): marks the current position in this input stream.
Boolean marksupported (): Tests whether this input stream supports the mark and reset methods.
void Reset (): repositions this stream to the last position when the mark method is called on this input stream.
As seen from the above, the read () method is an abstract modification, which is implemented by subclasses, and returns 1 when the end of the stream is reached.
Marksupported,mark,reset is generally used in conjunction with.
The available () method of InputStream returns the 0,close () method is an empty implementation, and the default marksupported () method returns FALSE.
The 1.1 bytearrayinputstream contains an input stream for an internal buffer.
Bytearrayinputstream inherits the InputStream and provides two constructors that are input in bytes.
Bytearrayinputstream implements its own read method, and overrides the Marksupported () method to return true, which means that the token is supported and the mark () and Reset () methods are supported.
On the other hand, Bytearrayinputstream's Close () method is null-implemented and is not useful, and the closed stream can be invoked without throwing ioexception.
1.2 fileinputstream Gets the input bytes from a file in the file system.
FileInputStream implements a partial method of InputStream, providing three construction methods to construct a file input stream.
And added two additional methods:
FileChannel Getchannel (): Returns the only FileChannel object associated with this file's input stream, which is often used by NiO using Java.
FileDescriptor getfd (): Returns a FileDescriptor object that represents a connection to the actual file in the file system, which is being used by this fileinputstream.
the 1.3 Pipeinputstream pipeline input stream should be connected to the pipeline output flow; The pipeline input stream provides all the data bytes to write to the pipeline output flow.
The pipeline input stream should be connected to the pipeline output flow, and the pipeline input stream provides all the data bytes to write to the pipeline output flow. Typically, data is read from a PipedInputStream object by a thread and written to the appropriate PipedOutputStream by another thread. It is not recommended that you try to use a single thread for both objects, because this could be a deadlock thread. The pipeline inflow contains a buffer that can be separated from the read and write operations within the bounds of the buffer.
Two additional methods are added:
void Connect (PipedOutputStream src): Causes this pipeline input to connect to the pipe output stream src.
protected void receive (int b): receives data bytes.
1.4 StringBufferInputStream is obsolete. This class failed to correctly convert characters to bytes.
1.5 Sequenceinputstream represents the logical concatenation of other input streams.
The Sequeneceinputstream starts with an ordered collection of input streams and reads from the first input stream until the end of the file is reached, then reads from the second input stream, and so on, until the end of the file containing the last input stream is reached.
1.6 ObjectInputStream Deserializes the base data and objects previously written with ObjectOutputStream.
ObjectInputStream inherits the InputStream, implements the ObjectInput interface, and the ObjectInput interface inherits the Datainput interface, which provides read operations on Java objects and basic data types.
ObjectInputStream (InputStream in): Creates ObjectInputStream read from the specified inputstream.
Note: Only objects that support the java.io.Serializable or Java.io.Externalizable interface can read from the stream.
1.7 FilterInputStream contains other input streams that use these streams as their basic data sources, which can transfer data directly or provide some additional functionality.
In Java, the use of the adorner pattern in IO redesign, FilterInputStream is the decorative role, and its subclasses are the specific decorative role, the FilterInputStream class itself simply overrides those who pass all requests to the included input stream All methods of InputStream. Subclasses of FilterInputStream can further rewrite some of the methods in these methods, and can also provide some additional methods and fields.
The 1.7.1 datainputstream data input stream allows applications to read basic Java data types from the underlying input stream in a machine-independent manner.
DataInputStream is a subclass of FilterInputStream, and it also implements the Datainput interface, which provides read operations on objects and basic types.
DataInputStream is not necessarily secure for multithreaded access.
1.7.2 Bufferedinputstream adds some functionality to another input stream, namely buffered input and the ability to support the mark and reset methods.
Bufferedinputstream inherits the FilterInputStream and creates an internal buffer array when the Bufferedinputstream is created. When you read or skip bytes in a stream, you can populate the internal buffer again from the included input stream as needed, filling in more than one byte at a time.
1.7.3 Pushbackinputstream adds performance to another input stream, which is the ability to push back or cancel read (unread) one byte.
While implementing the FilterInputStream partial approach, three additional methods are provided for "push-back" or "Cancel-read"
void Unread (byte[] b): Pushes back a byte array: before it is copied to the push-back buffer.
void Unread (byte[] B, int off, int len): pushes back a portion of a byte array: before it is copied to the push-back buffer.
void unread (int b): Pushes back one byte: before it is copied to the push-back buffer.
2. Abstract class for reading and writing stream of characters (Reader/writer)
Construction Method:
Protected Reader (): Creates a new character stream reader, and its important part synchronizes its own reader.
Protected reader (Object Lock): Creates a new character stream reader, and its important part synchronizes the given object.
Method:
abstract void Close (): Closes the stream and frees all resources associated with it.
int read (): reads a single character.
int read (char[] cbuf): reads the characters into the array.
abstract int Read (char[] cbuf, int off, int len): reads a character into a portion of an array.
int read (Charbuffer target): An attempt was made to read a character into the specified character buffer.
Boolean Ready (): Determines whether to read this stream.
void Reset (): Resets the stream.
void mark (int readaheadlimit): marks the current position in the stream.
Boolean marksupported (): Determines whether this stream supports the mark () operation.
Long Skip (long N): skips a character.
As you can see, the methods provided by reader and InputStream are basically similar, and the reader subclass must implement only read (char[], int, int) and close (), and the Ready () method returns false by default, Marksupported is not supported by default and can be overridden by subclasses.
There is a one by one correspondence between the known subclasses of Reader and InputStream, which is not listed here.
a few things to note about InputStream and reader:
1) for flow decorations, the byte stream uses FilterInputStream and filteroutputstream to modify the stream to meet special needs, while the class inheritance structure of the character stream continues to follow the same thought, but not exactly the same. BufferedWriter is not a filterwriter subclass. Filterwriter is an abstract class but does not have any subclasses, put it there only as a placeholder.
2) DataInputStream also provides the ReadLine () method, but this method has been deprecated, and the preferred way to read lines of text is to use the Bufferedreader.readline () method.
A program that uses the DataInputStream class to read lines of text can use the BufferedReader class instead, as long as the following form of code is used: DataInputStream d = new DataInputStream (in);
To be replaced by: bufferedreader d = new BufferedReader (new InputStreamReader (in));
3. Byte flow to the bridge of the character stream (InputStreamReader) and the character flows to the bridge of the Byte stream (outputstreamwriter)
InputStreamReader is a bridge of byte flow to a character stream that uses a character set that can be specified or explicitly given by name, or can accept the default character set of the platform.
Each call to a read () method in InputStreamReader causes one or more bytes to be read from the underlying input stream. To enable a valid conversion from byte to character, you can read more bytes in advance from the underlying stream to exceed the bytes required to satisfy the current read operation.
In order to achieve maximum efficiency, it is necessary to consider packaging InputStreamReader within the BufferedReader. For example:
BufferedReader in = new BufferedReader (new InputStreamReader (system.in));
Outputstreamreader and Inputstreamwriter are similar, here do not add to repeat.
Public Static voidReadFile (String fileName)throwsIOException {inputstream InputStream=NewFileInputStream (fileName); Final intLength = Inputstream.available ();//The estimated number of remaining bytes that can be read (or skipped) from this input stream without being blockedSYSTEM.OUT.PRINTLN ("Stream size >>>>>" +length); System.out.println ("Does the FileInputStream support the Marksupported () method:" +inputstream.marksupported ()); System.out.println ("========================================================"); //decorate the file stream as Bufferedinputstream, which gives us the mark and reset methodsBufferedinputstream Bufferedinputstream =NewBufferedinputstream (InputStream); System.out.println ("Does the Bufferedinputstream support the Marksupported () method:" +bufferedinputstream.marksupported ()); Bufferedinputstream.mark (0);//mark in No. 0 place CharFirstchar = (Char) Bufferedinputstream.read ();//reads the next byte of data, and returns 1 if the end of the stream is reachedSystem.out.println ("The first byte of a file is:" +Firstchar); CharSecchar = (Char) Bufferedinputstream.read ();//reads the next byte of data, and returns 1 if the end of the stream is reachedSystem.out.println ("The second byte of a file is:" +Secchar); Bufferedinputstream.reset ();//back to marker position CharAfterresetchar = (Char) Bufferedinputstream.read (); System.out.println ("The Reset method reads bytes after:" +Afterresetchar); Bufferedinputstream.reset (); System.out.println ("========================================================"); //one more wrapper to read characters // use DataInputStream wrapper to provide Java basic type and object read function DataInputStream DataInputStream =NewDataInputStream (Bufferedinputstream); String Firstutf = Datainputstream.readutf ();//Read the first Chinese characterSystem.out.println ("The first character of a file is:" +Firstutf); Datainputstream.reset ();//supported by BufferedinputstreamSystem.out.println ("========================================================"); InputStreamReader InputStreamReader=NewInputStreamReader (DataInputStream, "UTF-8");
// further decorate into reader, provide character related operation function, provide readline () BufferedReader BufferedReader=NewBufferedReader (InputStreamReader); String firstline = Bufferedreader.readline ();//read the first lineSystem.out.println ("The first line is:" +firstline); System.out.println ("========================================================"); LineNumberReader LineNumberReader=NewLineNumberReader (BufferedReader); System.out.print ("Current line number:" +Linenumberreader.getlinenumber ()); }
4. A self-contained class (Randomaccessfile) supports the reading and writing of random access files.
First look at the method definition of Randomaccessfile:
Public class Implements DataOutput, Datainput, closeable{}
As you can see, Randomaccessfile does not use any of the features that are already in InputStream and OutputStream, and is a separate class. It is suitable for files made up of well-known records, which can be transferred to another place using the Seek () method, then read or modify the record, which implements DataOutput and Datainput, which provides read and write functionality.
First look at the basic method of Datainput interface (DataOutput correspondence does not repeat):
Public InterfaceDatainput {voidReadfully (byte[] var1)throwsIOException; voidReadfully (byte[] var1,intVAR2,intVAR3)throwsIOException; intSkipbytes (intVAR1)throwsIOException; BooleanReadboolean ()throwsIOException; byteReadByte ()throwsIOException; intReadunsignedbyte ()throwsIOException; ShortReadshort ()throwsIOException; intReadunsignedshort ()throwsIOException; CharReadChar ()throwsIOException; intReadInt ()throwsIOException; LongReadlong ()throwsIOException; floatReadfloat ()throwsIOException; DoubleReaddouble ()throwsIOException; String ReadLine ()throwsIOException; String readUTF ()throwsIOException;}
Randomaccessfile constructor:
Randomaccessfile (file file, String mode): Creates a random-access file stream from which to read and write (optionally), which is specified by the file parameter.
Randomaccessfile (string name, String mode): Creates a random-access file stream from which to read and write (optionally), with the specified name.
Randomaccessfile has added its own methods on the basis of inheriting and implementing Datainput and DataOutput:
FileChannel Getchannel (): Returns the unique FileChannel object associated with this file.
FileDescriptor getfd (): Returns the opaque file descriptor object associated with this stream.
Long Getfilepointer (): Returns the current offset in this file.
void Seek (Long POS): Sets the offset of the file pointer measured to the beginning of this file, where the next read or write operation occurs.
void SetLength (Long newlength): Sets the length of this file.
Public Static voidRandomaccessfiletest ()throwsioexception{//Randomaccessfile used for reading large filesRandomaccessfile Randomaccessfile =NewRandomaccessfile ("C:\\users\\haisui\\desktop\\testio2.txt", "RW"); Randomaccessfile.writebytes ("Hello World"); Randomaccessfile.writeboolean (false); Randomaccessfile.writeutf (Hello "); Randomaccessfile.seek (12);//Skip Hello World BooleanBooleanread =Randomaccessfile.readboolean (); System.out.print ("Read Boolean:" +booleanread); Randomaccessfile.seek (0); String Firstline=Randomaccessfile.readline (); System.out.print (The pointer moves to the first byte to read one line: "+firstline); Randomaccessfile.readboolean (); String Utfread=Randomaccessfile.readutf (); System.out.print ("Read character:" +utfread); }
Overview of IO Basics in Java