Io (input and output) operations in java (IV), iooutput

Source: Internet
Author: User
Tags object serialization

Io (input and output) operations in java (IV), iooutput
The main operations of java io have been completed.
This section describes other content about java io.

Serializable serialization
Instance 1: Object serialization
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. ObjectOutputStream;
Import java. io. Serializable;
@ SuppressWarnings ("serial ")
// To serialize a class, you must implement the Serializable interface.
Class Person implements Serializable {
Private String name;
Private int age;
Public Person (String name, int age ){
This. name = name;
This. age = age;
}
Public String toString (){
Return "Name:" + this. name + ", Age:" + this. age;
}
}
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
Person p1 = new Person ("zhangsan", 12 );
Person p2 = new Person ("lisi", 14 );
// Here, the reference for creating a file write stream is intended for the ObjectOutputStream constructor.
FileOutputStream fos = null;
ObjectOutputStream oos = null;
Try {
Fos = new FileOutputStream (path );
Oos = new ObjectOutputStream (fos );
// You can write objects or other types of data here.
Oos. writeObject (p1 );
Oos. writeObject (p2 );
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
Oos. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}

Object serialization is to store an object for persistence, so that its attributes can be easily retained.
In layman's terms, an object is pulled out of the heap memory and put on the hard disk.
Of course, if you are happy, you can serialize other things, including arrays and basic data types.
Let's take a look at the content ......

 
Instance 2: deserialization of Objects
Copy codeThe Code is as follows:
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. IOException;
Import java. io. ObjectInputStream;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
// Well, the code here is really a bit long, and you need to throw exceptions or something.
// If you are also tired of reading it, you can leave it on the main method, and use an anonymous object in the constructor.
// What? Don't tell me you don't know about anonymous objects
FileInputStream FCM = null;
ObjectInputStream ois = null;
Try {
FCM = new FileInputStream (path );
Ois = new ObjectInputStream (FCM );
// The returned Object is actually an Object class Object.
// As we know it is a Person object
// Therefore, It is transformed downward in the local environment.
Person p = (Person) ois. readObject ();
System. out. println (p );
// Get rid of you ~!!!
} Catch (IOException e ){
E. printStackTrace ();
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
} Finally {
Try {
// Remember to close the downstream
Ois. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}

You see, we store an object on the hard disk for future use.
Now you need it. Naturally, you have to take it out.


Pipeline Flow
Instance 3: thread Communication
Copy codeThe Code is as follows:
Import java. io. IOException;
Import java. io. PipedInputStream;
Import java. io. PipedOutputStream;
// Implement the Runnable interface to implement a read thread
Class Read implements Runnable {
Private PipedInputStream in;
// Spread the pipeline to be read to the constructor
Public Read (PipedInputStream in ){
This. in = in;
}
// Implement the read thread
Public void run (){
Try {
Byte [] buf = new byte [1, 1024];
Int temp = 0;
// Read cyclically
// Read is a blocking method and an exception needs to be thrown.
// Add the printed stream code here
// If no data is read, the printed code is invalid.
While (temp = in. read (buf ))! =-1 ){
String str = new String (buf, 0, temp );
System. out. println (str );
}
} Catch (IOException e ){
// In fact, a custom exception should be thrown here
// I haven't figured it out yet
E. printStackTrace ();
} Finally {
Try {
// I have been fired. It is only important to remind myself of exceptions.
In. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
// Implement a write class
Class Write implements Runnable {
Private PipedOutputStream out;
// Pass in the pipeline Input
Public Write (PipedOutputStream out ){
This. out = out;
}
Public void run (){
Try {
// Write data here
Out. write ("pipeline output". getBytes ());
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
// Actually, you can write this close method into the above try.
// However, this is strange, and the logic is not very good.
Out. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
Public class Demo {
Public static void main (String [] args ){
PipedInputStream in = new PipedInputStream ();
PipedOutputStream out = new PipedOutputStream ();
Try {
// Connect the MPs queue
In. connect (out );
// Create an object and enable the thread
// Put try... catch in the same way.
// The following operations are meaningless if no MPs queue is connected.
Read r = new Read (in );
Write w = new Write (out );
// Put the object that has implemented the run method into the thread for execution
New Thread (r). start ();
New Thread (w). start ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

Okay, I printed such a sentence, and it was annoying to discard exceptions. In order to pay attention to details ......


Pipeline stream may be hard to understand.
We know that byte streams and byte streams both require Arrays for stream transfer.
While pipeline streams directly concatenate two streams, sending data while receiving
However, how can we determine the consistency between sending and receiving in the two statuses of simultaneous communication?
Then, the thread is used, whether the receiver or the sender executes
It will always cause a thread to be blocked and wait for data from the other side to be passed over.
In general, the purpose of MPs queue flow is to achieve thread communication.
In addition, the PipedReader and PipedWriter classes have the same operating principles and will not be described here.
DataOutputStream and DataInputStream
Instance 4: Write of the basic data type
Copy codeThe Code is as follows:
Import java. io. DataOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
DataOutputStream d = null;
Try {
// An OutputStream class object needs to be input here
D = new DataOutputStream (new FileOutputStream (path ));
// Start writing the basic data type
D. writeInt (12 );
D. writeBoolean (true );
D. writeDouble (12.2223 );
D. writeChar (97 );
// Refresh the stream
D. flush ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
D. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}

Here, we cannot intuitively understand the content, because it uses byte streams instead of bytes streams.
We only need to know that this program has written the basic data type to the hard disk.


Instance 5: read of the basic data type
Copy codeThe Code is as follows:
Import java. io. DataInputStream;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. IOException;
Public class Demo {
Public static void main (String [] args ){
String path = File. separator + "home" + File. separator + "siu" +
File. separator + "work" + File. separator + "demo.txt ";
DataInputStream d = null;
Try {
D = new DataInputStream (new FileInputStream (path ));
// Read basic data types in storage order
System. 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 ();
}
}
}
}

Note that the data must be read in the write order; otherwise, a data printing error may occur.

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.