In the real world we always have to deal with different data sources:
- A byte array.
- String Object
- File.
- "Pipe", working in a similar way to the actual pipe.
- A sequence that has other kinds of components.
- Other data sources, such as interent connections. --from "Java Programming thought"
For the above data sources, Java IO provides a corresponding stream processing class, such as reading the file data source Fileinputstream,fileoutputstream, these classes inherit the abstract class InputStream, and re-implement the main interface. As a learning chapter of Java IO, this paper mainly analyzes byte-oriented IO and character-oriented IO.
byte-oriented
Byte-oriented bytes, as the name implies, are in bytes when they process the data stream. These stream-processing classes inherit the InputStream and OutputStream two abstract classes. Here's a simple look at the interfaces that these two parent classes have
InputStream
Public Abstract intRead ()/*reads the same byte from the input stream to B, returning the actual number of bytes read, possibly less than the length of B*/ Public intReadbyteb[])/*reads up to len bytes into byte array B, and the first read is stored in B[off], returning the number of bytes actually read*/ Public intReadbyteB[],intOffintlen)/*skips n bytes from the input stream, returning the actual skipped byte length*/ Public LongSkipLongN)/*mark the position of the current input stream, in conjunction with the Reset function, the Readlimit parameter indicates the length of bytes that can be read from the stream before mark expires*/ Public synchronized voidMarkintreadlimit) Public synchronized voidReset ()/*See if the mark feature is supported*/ Public BooleanMarksupported ()
The above is the interface of InputStream, the main function is to read the data from the stream, its subclasses are all the functions have their own implementation. To inherit some subclasses of InputStream (classes that exist only in IO packets), where FilterInputStream is an adorner class, he holds a InputStream object, So the class that inherits the FilterInputStream can add other functions. This is why we often use the combination of various streams.
New Bufferedinputstream ( new FileInputStream ( ""));
OutputStream
/*writes the low 8 bits of B to the output stream*/ Public Abstract voidWriteintbthrowsIOException/*writes a B-byte array to the output stream*/ Public voidWritebyteB[])throwsIOException/*writes Len-length bytes to the output stream with a start of off B*/ Public voidWritebyteB[],intOffintLenthrowsIOException
You can see that the OutputStream interface is to write bytes to the output stream, and for different data sources outputstream have the corresponding subclasses. Similar to Filterinputstream,filteroutputstream is also an adorner class to combine other streams to implement different functions. In addition, the System.out object we commonly use is a PrintStream instance.
Here's a brief introduction to some of the following classes:
Bytearrayinputstream/bytearrayoutputstream reads from the buffer byte array into the stream/writes the stream to a buffer byte array (a data source).
Fileinputstream/fileoutputstream reads data from a file to a stream/or writes a stream to a file (data source), often paired with FileOutputStream.
The Datainputstream/dataoutputstream reads/writes the base type data (Int,char,long) in a portable manner from the stream length.
Bufferedinputstream/bufferedoutputstream Each read/write buffer (default 8k) to avoid actual operation and increase efficiency.
An example of a deep copy of an input and output stream, written to a byte array, can also be written to another stream:
PublicObject deepcopy ()throwsexception{//BytearrayoutputstreamBytearrayoutputstream bo =NewBytearrayoutputstream (); ObjectOutputStream oo=NewObjectOutputStream (bo); Oo.writeobject ( This); //read out the new object generated by the binary streamBytearrayinputstream ba =NewBytearrayinputstream (Bo.tobytearray ()); ObjectInputStream Oi=NewObjectInputStream (BA); returnoi.readobject ();}Character oriented
The stream is processed in characters, with the input stream abstract class reader, and the output stream abstract class writer. Reader, writer does not completely replace InputStream, OutputStream, but it is more convenient to manipulate the text and character types of data (char that supports Unicode,java is Unicode). Reader, writer has an interface similar to InputStream, OutputStream, the main is to change the byte operation to char operation, not listed.
Reader:
protected Object lock; Public int throws IOException
Reader provides a lock lock property, and a read to Charbuffer operation. Lock by default is the reader object itself (this), so that subclass can use this object to synchronize the operation of the flow, which can achieve a finer granularity of synchronization operations (later learning thread synchronization to detail, here first ignored). Likewise charbuffer in studying NIO again to introduce.
Consider the inheritance structure of reader:
Most classes correspond to the stream class and do not explain the specific usage in detail. It is important to note that InputStreamReader uses the Streamdecoder class to convert a byte stream to a character stream, so there are several uses:
New BufferedReader (new InputStreamReader (system.in));
Writer:
Private Char[] writebuffer;protectedObject lock;Abstract Public voidWriteCharCbuf[],intOffintLenthrowsIOException; Public voidWrite (String str,intOffintLenthrowsIOException/*equivalent to write (Csq.tostring ())*/ PublicWriter Append (charsequence csq)throwsIOException
Writer adds some writes to string and Charsequence, WriteBuffer is used to temporarily hold a string or character array to be written to the stream, and the rest of the interfaces are similar to OutputStream. The class inheritance structure of writer is as follows:
Or just a few examples of streaming operations, these examples come from the idea of Java programming. These flow classes need to be used in combination to maximize their functionality.
Public classBufferedinputfile { Public Static voidMain (string[] args) {//System.out.print (Read ("Bufferedinputfile.java")); //memoryinput (Read ("Bufferedinputfile.java")); //basicfileout ("Bufferedinputfile.java");Storingandrecoveringdata (); } //Buffered input File Public Staticstring Read (string file) {BufferedReader breader; StringBuilder SB=NewStringBuilder (); Try{Breader=NewBufferedReader (Newfilereader (file)); String s; while((S=breader.readline ())! =NULL) {Sb.append (s+ "\ n"); } breader.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnsb.tostring (); } //Memory Input Public Static voidmemoryinput (String str) {Try{StringReader Srreader=NewStringReader (str); intC; while((C=srreader.read ())! =-1) System.out.print (Char) c); Srreader.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } //formatted Memory input Public Static voidFormattedmemoryinput (byte[] b) {DataInputStream in=NewDataInputStream (NewBytearrayinputstream (b)); Try { while(In.available ()! = 0)//use available to read media without, realize differentSystem.out.print ((Char) In.readbyte ()); In.close (); } Catch(IOException e) {//TODO auto-generated Catch blockSystem.out.println ("End"); } } //basic file output, in fact file output often uses BufferedWriter for better performance Public Static voidbasicfileout (String file) {Try{BufferedReader in=NewBufferedReader (Newfilereader (file)); PrintWriter pwriter=NewPrintWriter (NewFileWriter ("Test.txt")); intLineCount = 1; String String= ""; while((String=in.readline ())! =NULL) pwriter.println (LineCount++ + ":" +string); Pwriter.close (); In.close (); System.out.print (Read ("Test.txt")); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } //storage and recovery data DataOutputStream DataInputStream can be used in combination to ensure accurate reading of data Public Static voidStoringandrecoveringdata () {Try{DataOutputStream OutputStream=NewDataOutputStream (NewBufferedoutputstream (NewFileOutputStream ("Data.txt"))); Outputstream.writedouble (3.1415926); Outputstream.writeutf ("What a F"); Outputstream.writeutf ("Hello World"); Outputstream.close (); DataInputStream in=NewDataInputStream (NewFileInputStream ("Data.txt")); System.out.println (In.readdouble ()); System.out.println (In.readutf ()); System.out.println (In.readutf ()); In.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}Randomaccessfile
Randomaccessfile applies to files of known size records, and can be transferred using the Seek () method. The Randomaccessfile only implements the Datainput and DataOutput interfaces (so there are many operations such as readdouble (), writedouble (), which are not related to InputStream and OutputStream.
In JDK1.4, most functions of randomaccessfile are replaced by NIO storage mapping files.
See an example of the actual operation:
Public Static voidusingrandomaccessfile (String file) {Try{randomaccessfile Rfile=NewRandomaccessfile (file, "RW"); RW Read/write for(inti=0; i<7; ++i) {Rfile.writedouble (i*1.414); } Rfile.writeutf ("End"); Rfile.close (); Display (file); Rfile=NewRandomaccessfile (file, "RW"); Rfile.seek (5*8); Rfile.writedouble (47.000144); Rfile.close (); Display (file); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }} Public Static voidDisplay (String file)throwsIOException {randomaccessfile rfile=NewRandomaccessfile (file, "R"); R Read-only for(inti = 0; I < 7; ++i) {System.out.println ("Value" + i + ":" +rfile.readdouble ()); } System.out.println (Rfile.readutf ()); Rfile.close ();} Public Static voidMain (string[] args) {Usingrandomaccessfile ("Hh.txt");}
OUTPUT
Value 0:0.0
Value 1:1.414
Value 2:2.828
Value 3:4.242
Value 4:5.656
Value 5:7.07
Value 6:8.484
End
Value 0:0.0
Value 1:1.414
Value 2:2.828
Value 3:4.242
Value 4:5.656
Value 5:47.000144
Value 6:8.484
End
Java I/O parsing