Java IO7: Pipeline Flow, object flow

Source: Internet
Author: User
Tags object serialization serialization

Objective

The previous article mainly describes the file character input stream filewriter, file character output stream filereader, file byte output stream fileoutputstream, file byte input stream FileInputStream, these are common flow classes. Of course, in addition to these stream classes, Java also provides a lot of flow classes for users, this article looks at other streams.

Pipe flow

pipeline flow is primarily used to connect two threads of communication . Pipeline flow is also divided into byte stream (PipedInputStream, PipedOutputStream) and character stream (Pipedreader, PipedWriter). For example, a pipedinputstream must be connected to a PipedOutputStream object to generate a communication pipeline, PipedOutputStream write data to the pipeline, PipedInputStream read data from the pipeline. The pipeline flow works as shown in the following:

Let's look at the usage of the pipe flow. Since the pipeline flow is used for inter-thread communication, there is bound to be a send thread and a receive thread, with two threads interacting with the data through the pipeline flow. First write a thread that sends the data:

 Public classSenderImplementsrunnable{PrivatePipedOutputStream out =NewPipedOutputStream ();  PublicPipedOutputStream Getoutputstream () {returnOut ; }         Public voidrun () {String str= "Receiver, Hello!"; Try{out.write (str.getbytes ());//write data to the pipeline stream (send)Out.close (); }         Catch(IOException e) {e.printstacktrace (); }    }    }

When using the stream to write the data, pay attention to whether the stream supports direct write string, not the string of the GetBytes () method to get the byte of the strings. Now that there is a thread to send the data, here's a thread to receive the data:

 Public classReceiverImplementsrunnable{PrivatePipedInputStream in =NewPipedInputStream ();  PublicPipedInputStream getInputStream () {returnIn ; }         Public voidrun () {String s=NULL; byteB0[] =New byte[1024]; Try{            intLength =In.read (B0); if(-1! =length) {s=NewString (B0, 0, length); System.out.println ("Received the following message:" +s);        } in.close (); } Catch(IOException e) {e.printstacktrace (); }    }}

Two threads have, write a main thread, use the Connect method of the pipeline output stream to connect the pipeline output stream and the pipeline input:

 Public Static voidMain (string[] args) {Try{ Sender Sender=NewSender (); Receiver Receiver=NewReceiver (); Thread Senderthread=NewThread (sender); Thread Receiverthread=NewThread (receiver); PipedOutputStream out= Sender.getoutputstream ();//WritePipedInputStream in = Receiver.getinputstream ();//read outOut.connect (in);//send output to inputSenderthread.start ();    Receiverthread.start (); }     Catch(IOException e) {e.printstacktrace (); } }

The output should be obvious, as we all know that the receiving thread received the data sent from the sending thread through the pipeline flow output stream:

The following message was received: Receiver, Hello!

Note that PipedInputStream uses a 1024-byte fixed-size loop buffer, and the data written to PipedOutputStream is actually saved to the corresponding PipedInputStream internal buffer. When PipedInputStream performs a read operation, the data read actually comes from the internal buffer. If the corresponding PipedInputStream input buffer is full, any thread attempting to write to PipedOutputStream will be blocked. And the write-operation thread will block until the read-PipedInputStream operation deletes the data from the buffer.

This means that the thread that writes the data to PipedOutputStream should not be the only thread responsible for reading the data from the corresponding PipedInputStream (so there are two threads open for read and write respectively). Assume that the T thread attempts to write 2000 bytes of data to the corresponding PipedOutputStream in a call to the PipedOutputStream write () method once, before the T thread blocks, It can write up to 1024 bytes of data (the size of the PipedInputStream internal buffer). However, once T is blocked, the operation to read PipedInputStream can no longer occur because T is the only thread that reads PipedInputStream, so that the T thread is completely blocked.

Object Flow

Java provides ObjectInputStream, ObjectOutputStream these two classes for object serialization operations, these two classes are used to store and read the object's input and output stream class, as long as all the member variables in the object are stored, it is equal to save the object, You can then continue to use this object by reading the object from among the saved objects. ObjectInputStream, ObjectOutputStream can help developers to save and read the object member variable value of the process, but require read-write or stored objects must implement the Serializable interface.

To take a look at an example, let's start with an entity class person that implements the serializable interface:

 Public classPersonImplementsserializable{/*** Serialization*/    Private Static Final LongSerialversionuid = 7827863437931135333L; Private transientString name; Private intAge ; Private Final StaticString sex = "man";  PublicPerson (String name,intAge ) {         This. Name =name;  This. Age =Age ; }         PublicString toString () {return"Name:" + This. Name + ", Age:" + This. Age + ", Gender:" +sex; }}

Calling ObjectOutputStream and ObjectInputStream to write a serialization and deserialization method, I now have "Serializable.txt" under the D-Disk:

 Public Static voidMain (string[] args)throwsexception{File File=NewFile ("D:/serializable.txt");    Serializable (file);    deserializable (file);} //Serialization Object Methods Public Static voidSerializable (file file)throwsexception{outputstream outputFile=Newfileoutputstream (file); ObjectOutputStream Oos=NewObjectOutputStream (OutputFile); Oos.writeobject (NewPerson ("Zhang San", 25));    Oos.close ();} //Deserialization Object Method Public Static voidDeserializable (File file)throwsexception{InputStream inputfile=Newfileinputstream (file); ObjectInputStream Ois=NewObjectInputStream (inputfile); Person P=(person) ois.readobject (); SYSTEM.OUT.PRINTLN (P);}

Now run, the D-Disk under a "Serializable.txt", the contents of the file is:

See garbled, because after the serialization itself is in accordance with a certain binary format of the organization of files, these binary formats can not be recognized by text files, so garbled is normal.

Of course, the console also has output:

Name:NULL, Age: 25, Gender: man

This proves that member variables modified by transient are not serialized.

Java IO7: Pipeline Flow, object flow

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.