Java IO5: 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 class Sender implements runnable{    private pipedoutputstream out = new PipedOutputStream ();        Public PipedOutputStream Getoutputstream ()    {        return out;    }        public void Run ()    {        String str = "Receiver, hello!";        Try        {            out.write (str.getbytes ());//write data to the pipe 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 class Receiver implements runnable{    private pipedinputstream in = new PipedInputStream ();        Public PipedInputStream getInputStream ()    {        return in;    }        public void Run ()    {        String s = null;        byte b0[] = new byte[1024];        Try        {            int length = In.read (B0);            if ( -1! = length)            {                s = new String (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 void Main (string[] args) {    try    {Sender Sender        = new Sender ();        Receiver receiver = new receiver ();        Thread senderthread = new Thread (sender);        Thread receiverthread = new Thread (receiver);        PipedOutputStream out = Sender.getoutputstream (); Write        PipedInputStream in = Receiver.getinputstream ();//read out        out.connect (in);//Send output to input        Senderthread.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

serialization, which has been made quite clear in this article, is primarily a simple way to simply cross the flow of objects.

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 class person implements serializable{    /**     * serialization *     /    private static final long Serialversionuid = 78 27863437931135333L;        Private transient String     name;    private int age                    ;    Private final static String sex = "man";        Public person (String name, Int. age)    {        this.name = name;        This.age = age;    }        Public String 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 void Main (string[] args) throws exception{    File File = new file ("D:/serializable.txt");    Serializable (file);    deserializable (file);}    Serialized object method public static void serializable (file file) throws exception{    outputstream outputFile = new FileOutputStream (file);    ObjectOutputStream oos = new ObjectOutputStream (outputFile);    Oos.writeobject (New person ("Zhang San", +));    Oos.close ();}    Deserialization object method public static void deserializable (file file) throws exception{    inputstream inputfile = new FileInputStream (file);    ObjectInputStream ois = new ObjectInputStream (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 IO5: Pipeline Flow, object flow

Related Article

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.