Java Knowledge exploration One: About IO class Library

Source: Internet
Author: User

After the organization inspection, I suddenly found myself in the most commonly used Java also have a lot of not understand the place, real for arise a great pity, today deliberately take the time to record these bits, share with you

The first batch of knowledge points to be sorted out are as follows:

    1. Java IO Inquiry, the entire structure and development of Io, incidentally, accompanied by a company to write the breakpoint code learning.
    2. Java's exception mechanism, the exploration of compile-time exceptions and runtime exceptions.
    3. Javacommon package understanding, especially the collection package of some small views, in fact, the container, what kind of utils can not escape some basic categories, such as deposit, take, sort, security, calibration and so on.

Gossip not much, start today's topic, study the whole structure of IO

From the architecture, the IO system is divided into two modules, IO and NIO (non-blocking), Io was born before JDK1.4, JDK1.4, produced NiO, and borrowed the code from NIO to refactor part of Io, such as FileInputStream, which added the Getchannel () method to support NiO. Again, such as reader and FileReader basic with NiO all rewrite.

One, Think in IO

IO from the implementation, roughly divided into byte stream and character stream two kinds:

  1. The byte stream. The read and write manipulation of the file is in bytes, which is straightforward, that is, manipulating the byte,byte array. The corresponding unsigned integer, that is, the normal return value of the Read method range in [0,255], a limited range of return values have many advantages, the more representative one is can flow to do a simple zip implementation, the algorithm, the use of Huffman tree. Of course, a one-byte operation, the efficiency is not high, the use of buffer to improve a lot of efficiency. However, there is a problem with the byte stream, that is, in the operation of the text file, there will be a lot of code for coding, examples are as follows
    FileInputStream is =NewFileInputStream ("F:\\books\\base\\vim common instructions". txt "); byte[] Buff =New byte[Buffer_size]; intReadSize = 0;  while((readsize = Is.read (buff))! =-1) {System.out.println (readsize); if(readsize<1024){                byte[] tmp =New byte[ReadSize]; System.arraycopy (Buff,0, TMP, 0, readsize); System.out.print (NewString (tmp, "GBK")); }Else{System.out.print (NewString (Buff, "GBK")); }        }
  2. Character Stream. Using characters as a unit, the internal implementation of reader is actually a char or char array as a cache container. It's a lot easier to manipulate text files. The encoding takes the system default encoding format. Looking for a long time to find the code of said +_+, code hidden very deep, from the reader to find Imputstreamreader, and then to Streamdecoder to the CharSet in the NIO package, the final priority is to obtain the environment variables in the system, System.getproperties () can also be obtained, Windows7 Chinese version of the words, obtained is "file.encoding=gb18030"
    /*** Returns The default charset of this Java virtual machine. * * <p> The default charset is determined during virtual-machine startup and * typically depends upon the LO     Cale and CharSet of the underlying * operating system. *     * @returnA CharSet object for the default charset * *@since1.5*/     Public StaticCharset Defaultcharset () {if(Defaultcharset = =NULL) {        synchronized(Charset.class) {java.security.PrivilegedAction pa=NewGetpropertyaction ("File.encoding"); String CSN=(String) accesscontroller.doprivileged (PA); Charset CS=lookup (CSN); if(cs! =NULL) Defaultcharset=CS; ElseDefaultcharset= forname ("UTF-8"); }    }    returnDefaultcharset; }

The following is a detailed description of the byte stream

    1. InputStream and OutputStream are two abstact classes, and for byte-oriented streams all extend these two ribs (base class ^_^);

  1. FileInputStream, opening a stream of local files, commonly used, has 3 constructor methods
    Public fileinputstream (file file)
    Public FileInputStream (String name)
    Public FileInputStream (FileDescriptor fdobj) It is worth emphasizing that this construct is not directly used, filedescriptor equivalent to opening a file's handle, you can create another with one file stream, so that the created stream is equivalent to one. If one stream is closed, the other cannot be read.
  2. PipedInputStream, which must be used in conjunction with PipedOutputStream, must be used in two or more threads, similar to the producer consumer model, PipedOutputStream writes the data to a shared buffer array, Notifies the PipedInputStream to read.

    There are two things to note:

    A) When using the Read method of PipedInputStream, be aware that if the buffer does not have data, it will block the current thread and will not be stuck if it is running in the main thread.

    b) If the thread where the PipedOutputStream is stopped, then the resources used by PipedOutputStream will be recycled, causing the pipe "broken", and the PipedInputStream Read method will also error.

    "A pipe is said to being broken if A thread that were providing data bytes to the connected piped output stream is no Longer alive. ”

  3. FilterInputStream, itself cannot be instantiated, is the parent class of Bufferedinputstream and so on, actually does not create this class can also implement its subclass, this kind of internal method is almost all the method of reusing the parent class. In fact, the meaning of its existence is more representative of an abstraction, meaning that the return data is repackaged or processed on the basis of InputStream, and the reasons for processing may vary, so that different subclasses are present.

  4. Linenumberinputstream, this class is a byte stream and character stream transformation in the failure of the product, has been determined to be discarded, the reason for abandonment is to force in the byte stream judgment read newline, regardless of coding problems. First, no matter whether the function can be realized, first from the level of abstraction is deficient. Move to the character stream and you will be happy. The corresponding linenumberreader of this class can be used. See LineNumberReader for details.

  5. DataInputStream, directly read the target file of byte, splicing or converting byte to other basic types, such as the following method

     Public Final intReadInt ()throwsIOException {intCH1 =In.read (); intCH2 =In.read (); intCH3 =In.read (); intCH4 =In.read (); if((ch1 | ch2 | CH3 | CH4) < 0)            Throw Neweofexception (); return((ch1 << +) + (CH2 << +) + (CH3 << 8) + (CH4 << 0)); }
    For basic types this can be converted, but for float and double, the native method in the float class and the double class is used to convert to the bottom of the operating system.
     Public Final Double throws IOException {    return  double.longbitstodouble (Readlong ());    }
    The only implementation of the more complex is the readUTF method, need to read all the data, must be in accordance with the format, you need to use DataOutputStream writeUTF to write the corresponding. DataInputStream in the actual use, or should be used with dataoutputstream, otherwise, the meaning is not very large.
  6. Bufferedinputstream, Initializes a 8192-size cache, improves efficiency, and calls the API without any difference, only reducing the number of times the system data is read directly. The internal holds a common InputStream, only after the buffer is empty, the real call InputStream read to write full buffer, so directly with the Bufferedinputstream read method can improve efficiency.
    What's interesting is that this class uses a Atomicreferencefieldupdater object to update and replace the volatile type buffer byte array, and the Compareandset method of this class is compared and updated with atomic properties.
    /*** Atomic Updater to provide compareandset for BUF. This was * necessary because closes can be asynchronous. We Use nullness * of buf[] As primary indicator the this stream is closed.     (The * "in" field is also nulled off on close.) */    Private Static FinalAtomicreferencefieldupdater<bufferedinputstream,byte[]> Bufupdater =Atomicreferencefieldupdater.newupdater (bufferedinputstream.class,byte[].class, "BUF");//Create Atomic updater .../*** Fills The buffer with more data, taking to account * shuffling and other tricks for dealing with marks.     * assumes that it's being called by a synchronized method.     * This method also assumes the all data have already been read in, * hence POS > count. */    Private voidFill ()throwsIOException {byte[] buffer =Getbufifopen (); if(Markpos < 0) Pos= 0;/*no mark:throw away the buffer*/    Else if(POS >= buffer.length)/*No in Buffer*/        if(Markpos > 0) {/*can throw away early part of the buffer*/        intSZ = pos-Markpos; System.arraycopy (buffer, markpos, buffer,0, SZ); POS=sz; Markpos= 0; } Else if(Buffer.length >=marklimit) {Markpos=-1;/*buffer got too big, invalidate Mark*/POS= 0;/*Drop Buffer Contents*/        } Else{/*Grow Buffer*/        intNsz = pos * 2; if(Nsz >marklimit) Nsz=Marklimit; byteNbuf[] =New byte[Nsz]; System.arraycopy (Buffer,0, Nbuf, 0, POS); if(!bufupdater.compareandset ( This, buffer, nbuf)) {//For update comparison, if the BUF object and buffer are the same, then update, different, not update//Can ' t replace BUF if there is an async close. //Note:this would need to be changed if fill ()//Is ever made accessible to multiple threads. //the only-to-do CAS can fail is via close. //assert buf = = null;                    Throw NewIOException ("Stream closed"); } Buffer=Nbuf; } Count=POS; intn = Getinifopen (). Read (buffer, POS, buffer.length-POS); if(N > 0) Count= n +POS; }
  7. Pushbackinputstream, characterized by the unread () method, the function is to read the flow of the process of self-added byte or byte array, re-read, the novel randomly inserted ad URL can be used this implementation, Sudden inserts a urlbyte array during the reading process, which is also convenient.
  8. Bytearrayinputstream, characterized by memory operation, the data read all in the cache array, the construction method is as follows
     Public Bytearrayinputstream (byte  buf[]) public bytearrayinputstream (byteint int length)
  9. Sequenceinputstream, the construction time can see multiple streams splicing, sequentially read, which contains the flow will be automatically closed, at the time of the call to close
     Public intRead ()throwsIOException {if(in = =NULL) {        return-1; }    intc =In.read (); if(c = =-1) {nextstream ();//after reading a stream, automatically change the next one, but this method is not thread-safe, two tune together, the consequences are very serious        returnread (); }    returnC; }/*** Continues reading in the next stream if a EOF is reached. */    Final voidNextstream ()throwsIOException {if(In! =NULL) {in.close (); }        if(E.hasmoreelements ()) { in=(InputStream) e.nextelement (); if(in = =NULL)                Throw NewNullPointerException (); }        Elsein =NULL; }
  10. StringBufferInputStream, this class has been discarded because of the erroneous conversion of byte stream to character stream, ignoring the coding problem. It is worth mentioning that the basic method of all parts of this class is thread-safe. This method is also referenced in a class of swing.
  11. ObjectInputStream, this class can be said to be more
        1. Implements two interfaces, Objectinut: Defines the types that can be read, Objectstreamconstants: Defines constants for reading file types, uses ReadObject to distinguish what type of object is read, and reads from serialized objects , it is necessary to judge what object is read by the flag bit, and this constant defines these values, all of which are short.
        2. has an inner class blockdatainputstream, the function of this class is to read the basic type of data when caching, in order to improve efficiency, but also caused problems, http://www.tuicool.com/articles/v6RNNr Deserialization and serialization note that it is recommended to use Read (Byte[],start,end) instead of a simple read (byte[]), using the latter, there may be read garbled, content errors and other issues, especially audio and video, may appear a murmur, Because ObjectInputStream is based on a single byte to determine the data type, it must be accurate.

Java Knowledge exploration One: About IO class Library

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.