Java (jdk1.7) IO series 01 InputStream and OutputStream Parsing

Source: Internet
Author: User

1.InputStream and OutputStream Introduction

In Java, InputStream and outputstream represent byte input streams and byte output streams, respectively, representing bytes of process or program communication, InputStream is an input stream, representing bytes from a file (FileInputStream ) or byte array (bytearrayinputstream), the corresponding OutputStream is the output stream, which represents the byte-to-file (FileOutputStream) or byte array ( Bytearrayoutputstream), such as write data, InputStream and OutputStream are all byte-stream superclass, define the bytes input stream and byte output stream abstract method and common implementation, here using the template mode in design mode, The superclass defines some common implementations and the constraints of the associated methods, which are implemented by subclasses. Let's look at some inputstream and OutputStream source code

2.InputStream Source Code Analysis
1  Packagejava.io;2  Public Abstract classInputStreamImplementscloseable {3 4     //defines the maximum number of bytes that can be skipped5     Private Static Final intMax_skip_buffer_size = 2048;6 7    //an abstract read method that defines a method constraint that reads a byte, allowing subclasses to implement,8      Public Abstract intRead ()throwsIOException;9 Ten   //places the bytes read into a byte array, returning the number of bytes read One      Public intReadbyteB[])throwsIOException { A         returnRead (b, 0, b.length); -     } -     //The specific read byte-to-byte array is implemented and provides read to byte array B from the start position of the off and read-in length Len the      Public intReadbyteB[],intOffintLenthrowsIOException { -         if(b = =NULL) { -             Throw Newnullpointerexception (); -}Else if(Off < 0 | | Len < 0 | | len > B.length-off) { +             Throw Newindexoutofboundsexception (); -}Else if(len = = 0) { +             return0; A         } at         //reads a byte first, if returns 1, indicates that there is no data in the current stream and returns 1 directly -         intc =read (); -         if(c = =-1) { -             return-1; -         } -        //If there is data, save the data in B inB[off] = (byte) C; -  to         inti = 1; +         Try { -             //by looping through and then depositing the contents of the read into the incoming buffer the              for(; i < Len; i++) { *c =read (); $             //If 1 is returned, the current read to the end of the filePanax Notoginseng                 if(c = =-1) { -                      Break; the                 } +B[off + i] = (byte) C; A             } the}Catch(IOException ee) { +         } -         returnI//returns the number of bytes read $     } $  -     //returns the number of bytes that were actually skipped -      Public LongSkipLongNthrowsIOException { the          -         LongRemaining =N;Wuyi         intnr; the         //if the current requirement skips 0, the 0 is returned directly -         if(n <= 0) { Wu             return0; -         } About         //the size of the character buffer cannot be greater than 2048. The number of skipped n may be greater than 2048. $       //Here's a reason why you don't directly declare an array that is the same size as skipping byte N. Because memory is a very expensive resource, if a file is large, you declare a large amount of memory in memory at a time , -       //on the one hand, it consumes a lot of memory, on the other hand it also affects garbage collection -  -  A         intSize = (int) Math.min (max_skip_buffer_size, remaining); +         byte[] Skipbuffer =New byte[Size];//defines the number of bytes skipped by a buffered record the          while(Remaining > 0) { -             //if the number of skipped is greater than 2048, the number of skips is computed by performing the Read method multiple times through the buffer $NR = Read (Skipbuffer, 0, (int) math.min (size, remaining)); the             if(Nr < 0) { the                  Break; the             } theRemaining-=nr; -         } in        //returns the number of bytes actually skipped the         returnN-remaining; the     } About     //returns how much data is available to read the      Public intAvailable ()throwsIOException { the         return0; the     } +  -     //close the stream and leave the subclass to implement the      Public voidClose ()throwsIOException {}Bayi  the    //mark a location and then perform the Reset method to return to the location of the marker the      Public synchronized voidMarkintreadlimit) {} -  -    //re-read from the Mark's location the      Public synchronized voidReset ()throwsIOException { the         Throw NewIOException ("Mark/reset not supported"); the     } the  -     //Indicates whether the tagging feature is supported the      Public Booleanmarksupported () { the         return false; the     }94  the}

3.OutputSteam Source Code Analysis
1  Public Abstract classOutputStreamImplementscloseable, flushable {2     //writes a byte b to the input stream3      Public Abstract voidWriteintbthrowsIOException;4 5    //writes bytes in byte array b to the input stream6      Public voidWritebyteB[])throwsIOException {7Write (b, 0, b.length);8     }9 Ten    //writes bytes in byte array b to the input stream and provides control parameters to start reading from that position in the byte array, and how long to read One      Public voidWritebyteB[],intOffintLenthrowsIOException { A         if(b = =NULL) { -             Throw Newnullpointerexception (); -}Else if((Off < 0) | | (Off > B.length) | | (Len < 0) | | the((off + len) > b.length) | | ((off + len) < 0)) { -             Throw Newindexoutofboundsexception (); -}Else if(len = = 0) { -             return; +         } -          for(inti = 0; i < Len; i++) { +Write (B[off +i]); A         } at     } -  -     //refreshes the output stream, forcing the bytes in the character buffer to be written from memory to the output stream, if the output stream is memory such as Bytearrayoutputstream, then the implementation is empty -  -      Public voidFlush ()throwsIOException { -     } in  -     //closes the output stream and frees the resource if the subclass does not need it, and the implementation is empty to      Public voidClose ()throwsIOException { +     } -  the}

4. Conclusion

Although the implementation of the two abstract classes of InputStream and OutputStream is relatively simple and the amount of code is relatively small, we can learn something from it, such as the use of template design patterns, the validation logic of the method parameters in the code, and so on. A lot of experience other people write code, will always learn something, maybe now do not see what is the use, but the impact on you can be seen slowly.

===============================================================

Work hard, live with your heart

===============================================================

Java (jdk1.7) IO series 01 InputStream and OutputStream Parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.