How does Java write the input stream into a file through serialization or transmit it through socket?

Source: Internet
Author: User

As we all know, java. Io. inputstream cannot be serialized, but how to serialize a class with inputstream? You can change the stream to a byte array. the serialization mechanism is used here.

The Java. Io. serializable API has the following description:

Classes that require special processing during serialization and deserialization must use the following accurate signatures to implement special methods:

 
Private void writeobject (Java. Io. objectoutputstream out) throws ioexception private void readobject (Java. Io. objectinputstream in) throws ioexception, classnotfoundexception;

The writeobject method is used to write the state of the object of a specific class so that the corresponding readobject method can restore it. By calling
Out. defaultwriteobject can call the default mechanism for saving the object fields. This method does not need to involve the status of its superclass or subclasses. The status is
The writeobject method or the method supported by dataoutput for the basic data type writes each field to objectoutputstream for storage.

The following uses this mechanism to implement: Import java. Io .*;
Public class test {
Public static void main (string... arguments) throws exception {
If (arguments. length! = 1 ){
System. Out. println ("Usage: Java test [w | r]");
Return;
}
String option = arguments [0];
If ("W". equalsignorecase (option )){
Fileoutputstream Fos = NULL; // serialized File
Objectoutputstream OOS = NULL; // serialized File
Fileinputstream FD = NULL; // file stream read
Try {
Fos = new fileoutputstream ("A. dat ");

Oos = new objectoutputstream (FOS );

FCM = new fileinputstream ("Liu Yan-Broken Bridge umbrella ");
Document Doc = new document ("Broken Bridge umbrella", FCM );
Oos. writeobject (DOC );
} Finally {
If (OOS! = NULL ){
Oos. Close ();
}
If (FOS! = NULL ){
FOS. Close ();
}
If (FS! = NULL ){
FCM. Close ();
}
}



} Else if ("r". inclusignorecase (option )){
Fileinputstream FCM = NULL;
Objectinputstream OIS = NULL;
Try {
FCM = new fileinputstream ("A. dat ");
Ois = new objectinputstream (FCM );

Document Doc = (document) Ois. readobject ();
Doc. SaveFile ();
} Finally {
If (OIS! = NULL ){
Ois. Close ();
}
If (FS! = NULL ){
FCM. Close ();
}
}
} Else {
System. Out. println ("Usage: Java test [w | r]");
}
}
}

Class document implements serializable {
Private string filename;

// Inputstream cannot be serialized
Private transient inputstream;

Public document (string filename, inputstream) {arrears
If (filename = NULL | filename. Trim (). Length () = 0 | inputstream = NULL ){
Throw new illegalargumentexception ("filename:" + filename + "| inputstream:" + inputstream );
}
This. filename = filename;
This. inputstream = inputstream;
}

Private void readobject (objectinputstream OIS) throws ioexception, classnotfoundexception {
System. Out. println ("readobject called ");
Ois. defaultreadobject (); // read deserialized content

// Read the stream
Bytearrayoutputstream baos = new bytearrayoutputstream ();
Byte [] buffer = new byte [1024];
Int ret =-1;
While (ret = Ois. Read (buffer, 0, 1024 ))! =-1 ){
Baos. Write (buffer, 0, RET );
}
Byte [] DATA = baos. tobytearray ();

Inputstream = new bytearrayinputstream (data );

}

Private void writeobject (objectoutputstream OOS) throws ioexception {
System. Out. println ("writeobject called ");
Oos. defaultwriteobject (); // write serializable content to the stream
Women's brand list
// Write the inputstream
Byte [] buffer = new byte [1024];
Int ret =-1;
While (ret = inputstream. Read (buffer, 0, 1024 ))! =-1 ){
Oos. Write (buffer, 0, RET );
}
Oos. Flush ();
}

Public void SaveFile () throws ioexception, filenotfoundexception {
Fileoutputstream Fos = NULL;
Try {
Fos = new fileoutputstream (filename );

Byte [] buffer = new byte [1024];
Int ret =-1;
While (ret = inputstream. Read (buffer, 0, 1024 ))! =-1 ){
FOS. Write (buffer, 0, RET );
}
} Finally {
If (FOS! = NULL ){
FOS. Close ();
}
}
}
}

Put an MP3 file in the same directory of the test. Class file. I used: Liu Yanyan-Broken Bridge umbrella.

The document class is a serializable class that includes two fields: the input stream and a file name filename. You can call the SaveFile method of the Class Object to save the data in the input stream to a file named filename.

When Java test W is executed, a document class instance is serialized and written to the file, including the data of "Liu Yan-Broken Bridge umbrella.

Execute Java test R to read the document object from the serialized file previously written, and then call the SaveFile Method on it to save the data.

Generally, we seldom need to add the readobject and writeobject methods to the serializable class. Here, to write the inputstream word
The two methods are added to the data section. The signatures of these two methods must be the same as those described above. Otherwise, they will not be called during serialization or deserialization, so during testing, always print a sentence to ensure the two
Methods are indeed called during serialization or deserialization.

Writing inputstream data to a serialized file is easy. It reads bytes from inputstream and then writes them to objectoutputstream.

Reading data from a serialized file is also true. After a serializable field is read, the byte is then read from objectinputstream.

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.