Java IO working Mechanism analysis

Source: Internet
Author: User

Java's IO classes are all under the java.io package, and these classes can be broadly divided into the following 4 types:

    1. Byte-based operation of I/O interfaces: InputStream and OutputStream
    2. I/O interfaces based on character manipulation: Writer and Reader
    3. Disk operation-based I/O interface: File
    4. Network operation-based I/O interface: Socket
1 basic structure of the IO Class Library 1.1 IO interface based on byte operations

The IO interfaces based on byte operations are InputStream and Outputstream,inputstream, respectively, as shown in the class structure diagram below:

Similar to InputStream, the OutputStream class also has the same class structure diagram.

The use of each subclass can refer to the API documentation for the JDK, and here's what we need to note: The way data is manipulated can be combined as follows:

New InputStreamReader (new FileInputStream ("H:\\haha.txt"), "Utf-8");

From the above code can be seen, InputStreamReader can read from the FileInputStream data, from the source can be seen, in fact, not only inputstreamreader, all the IO class can be combined in this way to use.

It is also important to note that the flow will have to be written to the final location, disk or network, from the OutputStream class diagram can be seen in the write network is actually a write file operation, but the bottom is transmitted over the network.

1.2 Character-based IO operation interface

Whether it is disk or network data transmission, is in bytes, but the general common data operations in the program are in characters (char in Java occupies 2 bytes, C + + char occupies 1 bytes), which requires that we have an IO interface to manipulate characters, To deal with the encoding conversion problem of character and Byte, that is, the write and reader interfaces and their implementation classes, and their class interface diagrams are as follows:

The most important way to read a character interface reader is read (), which reads the characters and returns the number of characters read, either writer or reader, which defines only the way in which the data characters are read or written, that is, how to write or read, but there is no provision for the data to be written to ( such as disk or network).

1.3 byte-to-character conversion interface

Sometimes data persistence and network transmission are performed in bytes, and all require the conversion of bytes and characters to each other.

/*** Use FileReader to read files*/@Test Public voidTestfilereader ()throwsIOException {filereader FileReader=NewFileReader ("H:\\haha.txt"); Char[] Buff =New Char[512]; StringBuffer StringBuffer=NewStringBuffer ();  while(Filereader.read (Buff) > 0) {stringbuffer.append (buff);    } filereader.close (); System.out.print (Stringbuffer.tostring ());}/*** Use FileReader to read the file and then FileWriter write to another file*/@Test Public voidTestfilereaderandfilewriter ()throwsIOException {filereader FileReader=NewFileReader ("H:\\haha.txt"); Char[] Buff =New Char[512]; StringBuffer StringBuffer=NewStringBuffer ();  while(Filereader.read (Buff) > 0) {stringbuffer.append (buff);    } System.out.println (Stringbuffer.tostring ()); FileWriter FileWriter=NewFileWriter ("H:\\haha2.txt");    Filewriter.write (stringbuffer.tostring (). Trim ());    Filewriter.close (); System.out.println ("Write file succeeded");}/*** Use InputStreamReader to read files*/@Test Public voidTestinputstreamreader ()throwsIOException {inputstreamreader InputStreamReader=NewInputStreamReader (NewFileInputStream ("H:\\haha.txt"), "Utf-8"); Char[] Buff =New Char[512]; StringBuffer StringBuffer=NewStringBuffer ();  while(Inputstreamreader.read (Buff) > 0) {stringbuffer.append (buff); } System.out.println (Stringbuffer.tostring ());} @Test Public voidTESTINTPUTSTREAM2 ()throwsIOException {inputstreamreader InputStreamReader=NewInputStreamReader (NewStringBufferInputStream ("Hello World")); Char[] Buff =New Char[512]; intn =inputstreamreader.read (Buff);    SYSTEM.OUT.PRINTLN (n); SYSTEM.OUT.PRINTLN (buff);}/*** Use InputStreamReader to read the file and then OutputStreamWriter write to another file*/@Test Public voidTestoutputstreamwriter ()throwsIOException {inputstreamreader InputStreamReader=NewInputStreamReader (NewFileInputStream ("H:\\haha.txt"), "Utf-8"); Char[] Buff =New Char[512]; StringBuffer StringBuffer=NewStringBuffer ();  while(Inputstreamreader.read (Buff) > 0) {stringbuffer.append (buff);    } System.out.println (Stringbuffer.tostring ()); OutputStreamWriter OutputStreamWriter=NewOutputStreamWriter (NewFileOutputStream ("H:\\haha2.txt"), "Utf-8");    Outputstreamwriter.write (stringbuffer.tostring (). Trim ()); Outputstreamwriter.close ();}

Note: The FileReader class inherits the Inputstreamreader,filereader read file stream, which is decoded by Streamdecoder to Char, and its decoded character set uses the default character set. In Java, we should use the file object to determine if a file exists, and if we open it with FileOutputStream or filewriter, it will definitely be overwritten.

2 synchronous and asynchronous, blocking, and non-blocking

Synchronous and asynchronous are for IO. The so-called synchronization is the completion of a task needs to rely on another task, only wait for the task to be relied upon to complete, the dependent task can be counted, this is a reliable task sequence. Either success succeeds, failure fails, and the state of the two tasks remains the same. Asynchronous is not required to wait for the task to be relied upon to complete, but to inform the dependent task to complete what work, dependent on the task is immediately executed, as long as the completion of the entire task, even if completed. As to whether the dependent task is ultimately completed, the task that relies on it cannot be determined, so it is an unreliable task sequence. We can use the phone and texting to be a good metaphor for synchronous and asynchronous operations.

Blocking and non-blocking are for the CPU. Blocking and non-blocking are mostly from CPU consumption, and blocking is the CPU stopping to wait for a slow operation to complete the CPU before doing anything else. Non-blocking is when the slow operation is performed by the CPU to do other things, and when this slow operation completes, the CPU then completes the subsequent operation. Although the apparent non-blocking way can significantly improve the CPU utilization, but also with the other consequence is the system's thread switching increased. Increased CPU usage can compensate for the switching cost of the system needs to be evaluated well.

3 serialization

The object serialization of Java converts objects that implement the serializable interface into a sequence of bytes, and is able to restore the sequence of bytes to its original object at a later time. This process can be done over the network, so that the serialization mechanism can automatically compensate for differences between different operating systems. The clever thing about serialization is that it not only preserves the "panorama" of the object, but also keeps track of the references that the object contains and saves the objects, and then the ability to eventually make each such reference contained within the object, and so on.

To instantiate an object, first create some OutputStream objects, and then encapsulate them within a ObjectOutputStream object, which is to serialize the object and send it to OutputStream (by calling WriteObject ()). Object serialization is byte-based, so the class hierarchy is inherited using InputStream and OutputStream. The deserialization and serialization process is reversed, and a inputstream needs to be encapsulated within ObjectInputStream and then called ReadObject () to get a reference that points to an object that is being converted upward, so it must be transformed downward to set them directly. The following is the sample code for serialization and deserialization:

@Test Public voidtestwriteserialization () {Try {FileOutputStream FileOutputStream =NewFileOutputStream ("H:\\serialize.txt"); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (FileOutputStream); Objectoutputstream.writeobject ("Start"); Objectoutputstream.writeobject (NewPerson ("Luoxn28", 23)); Objectoutputstream.writeobject (12);    Objectoutputstream.close (); } Catch(IOException e) {e.printstacktrace (); } System.out.println ("End ...");} @Test Public voidtestreadserialization () {Try{FileInputStream FileInputStream=NewFileInputStream ("H:\\serialize.txt"); ObjectInputStream ObjectInputStream=NewObjectInputStream (FileInputStream); String Info1=(String) objectinputstream.readobject (); Person Person=(person) objectinputstream.readobject (); intnum = (int) Objectinputstream.readobject ();        System.out.println (INFO1);        SYSTEM.OUT.PRINTLN (person);    SYSTEM.OUT.PRINTLN (num); } Catch(IOException e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); }}

Resources:

1. In-depth analysis of the working mechanism of Java I/O

2. Java IO System

Java IO working Mechanism analysis

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.