Java io Flow Details (iv)

Source: Internet
Author: User

Serialization of Serializable
1 Serialization of objects

     class  person implements Serializable {        PrivateString name;Private intAge PublicPerson (String name,intAge) { This. name = name; This. Age = Age; } PublicString toString () {return "Name:"+ This. Name +", Age:"+ This. Age; }    } Public  class serialtest {         Public Static voidMain (string[] args) {String path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt"; person P1 =NewPerson ("Zhangsan", A); person P2 =NewPerson ("Lisi", -);//Create a file here to write a reference to the stream is to play with the ObjectOutputStream constructorFileOutputStream fos =NULL; ObjectOutputStream Oos =NULL;Try{fos =NewFileOutputStream (path); Oos =NewObjectOutputStream (FOS);//The object can be written here, or other types of data can be writtenOos.writeobject (p1);            Oos.writeobject (p2); }Catch(IOException e)            {E.printstacktrace (); }finally{Try{Oos.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }    }

Results:

2 deserialization

 PackageCom.yin.serialize;ImportJava.io.FileInputStream;ImportJava.io.IOException;ImportJava.io.ObjectInputStream; Public  class serialtestfan {     Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt";//Well, the code here is really a bit long, and throw something out of the ordinary .        //If you are tired of seeing it, just throw it in the main method and use the anonymous object in the construction method .        //What? Don't tell me you don't know. Anonymous ObjectFileInputStream FIS =NULL; ObjectInputStream Ois =NULL;Try{FIS =NewFileInputStream (path); OIS =NewObjectInputStream (FIS);//Return is actually an object class            //Because we know it's a person class object            //So, put it down in place.Person P = (person) ois.readobject ();            SYSTEM.OUT.PRINTLN (P);            person P2 = (person) ois.readobject (); System.out.println (p2);//person P3 = (person) ois.readobject ();//if (P3 = = null) {//System.out.print ("P3==null");//}else {//System.out.println (p3);//          }            ///Throw you to death, annoying ~!!! }Catch(IOException e)        {E.printstacktrace (); }Catch(ClassNotFoundException e)        {E.printstacktrace (); }finally{Try{//or remember to turn off the dirtyOis.close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }}

Results:

Corresponds to the object written at the time of serialization.
It is important to note that if the code of the comment is stripped of the comment, a eofexception exception occurs, that is, after the data object is read, it is not allowed to read down. Only how much object data is read by how many objects.

3 Pipe Flow
Communication of Threads

Package Com.yin.serialize;import Java.io.ioexception;import Java.io.pipedinputstream;import Java.io.PipedOutputStream;//Implement Runnable interface, implement a read threadClass Read implements Runnable {PrivatePipedInputStreaminch;// stream a pipeline that needs to be read into the constructor     Public Read(PipedInputStreaminch) { This.inch=inch; }//Implementation read this thread     Public void Run() {Try{byte[] buf =New byte[1024x768];inttemp =0;//Cyclic reading            //read is a blocking method that needs to throw an exception            //The code for the print stream is also added here            //Because if the data is not read, the printed code is not valid             while(temp =inch. Read (BUF))! =-1) {String str =NewString (BUF,0, temp); System. out. println (str); }        }Catch(IOException e) {//In fact, this should throw a custom exception            //I haven't figured it out yet .E.printstacktrace (); }finally{Try{//I've thrown the fire, just to remind myself that the anomaly is important.                inch. Close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }  }//Implement a write class hereClass Write implements Runnable {PrivatePipedOutputStream out;//Pipe input is circulated in     Public Write(PipedOutputStream out) { This. out= out; } Public void Run() {Try{//Start writing data here             out. Write ("Pipeline operation ========= see No, that's the sentence!! ". GetBytes ()); }Catch(IOException e)        {E.printstacktrace (); }finally{Try{//should actually be able to write this closing method in the try inside                //But it feels weird, it's not logical.                 out. Close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }} Public classDemo { Public Static void Main(string[] args) {PipedInputStreaminch=NewPipedInputStream (); PipedOutputStream out=NewPipedOutputStream ();Try{//Connection Piping            inch. Connect ( out);//Create object, open thread            //Here also put in Try...catch inside            //Because if there is no link to the channel, the following operation is meaninglessRead r =NewRead (inch); Write W =NewWrite ( out);//Put the object that has already implemented the Run method into the thread execution            NewThread (R). Start ();NewThread (W). Start (); }Catch(IOException e)        {E.printstacktrace (); }    }}

Results:

We know that both the byte stream and the character stream require arrays for streaming
And the pipeline flow is directly connected two streams, while sending data, while receiving
However, the two States of communication at the same time, how to determine the transmission and reception consistency?
Then, you need to use the thread, either the receiver or the sender, to perform the first
Always causes a blocking state for one thread, waiting for the other party's data to pass through.
In general, the purpose of pipeline flow, that is, for thread communication
In addition, there are Pipedreader and PipedWriter classes, the same principle of operation

4 DataOutputStream and DataInputStream class
Write to the base data type

 PackageCom.yin.serialize;ImportJava.io.DataOutputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException; Public  class datastreamtest {     Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt"; DataOutputStream d =NULL;Try{//You need to pass in a OutputStream class object hereD =NewDataOutputStream (NewFileOutputStream (path));//Start writing basic data TypesD.writeint ( A); D.writeboolean (true); D.writedouble (12.2223); D.writechar ( the);//Refresh streamD.flush (); }Catch(IOException e)            {E.printstacktrace (); }finally{Try{D.close (); }Catch(IOException e)                {E.printstacktrace (); }            }    }}

Results:

5 reading of the base data type

Import Java.io.datainputstream;import Java.io.fileinputstream;import java.io.IOException; Public classdatareadtest { Public Static void Main(string[] args) {String Path ="D:\\Program Files (x86) \\ADT\\workspace\\JavaIO\\demoTest.txt"; DataInputStream d =NULL;Try{d =NewDataInputStream (NewFileInputStream (path));//Read basic data types in order of storageSystem. out. println (D.readint ()); System. out. println (D.readboolean ()); System. out. println (D.readdouble ()); System. out. println (D.readchar ()); }Catch(IOException e)            {E.printstacktrace (); }finally{Try{D.close (); }Catch(IOException e)                {E.printstacktrace (); }            }    }}

Results:

This results in the same order as the data written above. That means reading data and writing data is consistent!! Attention! Otherwise, the data print error will occur!
Reference: http://www.cnblogs.com/nerxious/archive/2012/12/17/2822365.html

SOURCE download

Java io Flow Details (iv)

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.