JAVA 56th-serialization and deserialization of IO stream (10) Objects & amp; RandomAccessFile, io serialization

Source: Internet
Author: User

JAVA 56th-IO stream (10) Object serialization and deserialization & RandomAccessFile, io serialization

Operation object

ObjectInputStream and ObjectOutputStream

The operated object must implement Serializable (Mark Interface)

ObjectOutputStream writes the basic data types and graphics of Java objects to OutputStream. You can use ObjectInputStream to read (refactor) objects. Objects can be stored permanently by using files in the stream. If the stream is a network socket stream, you can reconstruct the object on another host or in another process.

The default serialization mechanism of an object writes the following content: the Object Class, Class signature, and values of non-transient and non-static fields. References to other objects (except transient and static fields) will also cause those objects to be written. You can use the reference sharing mechanism to encode multiple references of a single object so that the image of the object can be restored to the shape when they were originally written.

Object serialization

Public static void writeobj () throws IOException {// if it is a txt file, it is a bunch ..., generally, the suffix names are objectObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj. object "); // many frameworks are stored, which can be difficult to create and generally read oos. writeObject (new Perman ("a", 1); // only stores the object out of the hard disk to extend its lifecycle. close (); // complete object serialization. The serialized object must implement Serializable}

Note:

Writes the specified object to ObjectOutputStream. The signature of the Class and Class of the object, and the values of non-transient and non-static fields of the class and all its super types will be written.


Object deserialization

The purpose of storage is to read. FileInputStream can read the data of an object, but cannot be assembled into an object.

ObjectInputStream deserializes the basic data and objects previously written using ObjectOutputStream.

That is to say, ObjectInputStream can only read data written by ObjectOutputStream.

Readobject () reads an object once.

Public static void readobj () throws IOException, ClassNotFoundException {// if it is a txt file, it is a heap ..., generally, all suffix names are objectObjectInputStream ois = new ObjectInputStream (new FileInputStream ("obj. object "); Perman p = (Perman) ois. readObject (); // a System exception must be thrown. out. println (p. getName () + ":" + p. getAge (); ois. close ();}

It is generally used for specific database connection objects and objects that you do not want to create and want to retain


About Serializable

During serialization, a version number called serialVersionUID is used to associate with each serializable class, in the deserialization process, this serial number is used to verify whether the sender and receiver of the serialized object have loaded classes compatible with serialization for this object.

After an interface is implemented, the object will be serialized with an ID number. When the class changes (private int age: public int age, the system checks whether the received Class Object (after modification) is of the same version as the read Class Object (before modification), and does not throw an exception. InvalidClassException, And the ID number defines an ID number based on the class features and signatures.


PS: Serializable interface: Used to add an ID to the serialized class and determine whether the object is of the same version.


If the serialVersionUID is not explicitly declared for the serializable class, the default serialVersionUID value of the class is calculated based on all aspects of the class during the serialization runtime, as described in "Java (TM) Object serialization specification. However,Strongly recommendedAll serializable classes explicitly declare the serialVersionUID value because the calculation of the default serialVersionUID is highly sensitive to the detailed information of the class, which may vary according to the implementation of the compiler, this may cause exceptions in the deserialization process.InvalidClassException. Therefore, to ensure the consistency of serialVersionUID values across different java compilers, the serialization class must declare a clear serialVersionUID value. We strongly recommend that you useprivateThe modifier displays the Declaration serialVersionUID (if possible), because this declaration is only applicable to the direct Declaration class -- serialVersionUID field as an inherited member. The array class cannot declare a clear serialVersionUID, so they always have the default calculated value, but the array class does not match the serialVersionUID value.


The serializable class can be declared"serialVersionUID"(This field must be static and final)longType field) explicitly declare its own serialVersionUID:

 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
Any access modifier

Class Perman implements Serializable {private static final long serialVersionUID = 845645641123231l; // blind write + l // if the object wants to be serialized, the interface must be implemented to mark private String name; private int age; //.....} public static void readobj () throws IOException, ClassNotFoundException {// if it is a txt file, it is a heap ..., generally, all suffix names are objectObjectInputStream ois = new ObjectInputStream (new FileInputStream ("obj. object "); Perman p = (Perman) ois. readObject (); // a System exception must be thrown. out. println (p. getName () + ":" + p. getAge (); ois. close ();}


After this modification, the class changes, because the ID number is not changed, it can still be read and stored objects


Keyword transient (temporary)

When writing an object, some data in the object does not want to be written as hard disk. Use this keyword.

Class Perman implements Serializable {private static final long serialVersionUID = 845645641123231l; // blind write + lprivate transient String name; private int age ;......}

Transient: non-static data, serialized


Other classes of the IO package:

RandomAccessFile: random access to a file, which can be read and written.

Use skipBytes (int x) and seek (int x) to achieve random access.

Pipeline stream: PipedInputStream and PipedOutputStream

Input and output can be directly connected through the collection thread


RandomAccessFile

It is not a subclass of the IO system.

Features:

1. both read and write

2. The memory of this object maintains an array, and the elements in the array can be operated through pointers.

3. You can use the getFilePointer method to obtain the pointer position and use the seek method to set the pointer position.

4. Because it is a byte array, the object is actually a byte input stream and an output stream encapsulation.

5. Limitations. From the constructor, we can see that the source and sink can only be files.

Such instances support reading and writing random access files. Random access to files is similar to a large byte array stored in the file system. There is a cursor or index pointing to the hidden array, calledFile pointerThe input operation reads the byte starting from the file pointer and advances the object pointer as the byte is read. If a random access file is created in read/write mode, the output operation is also available. The output operation starts writing bytes from the file pointer and advances the file pointer as the bytes are written. The output operation after the current end of the hidden array causes the array to expand. The file pointer can be passed throughgetFilePointerMethod to read and passseekMethod settings.

Constructor Summary
RandomAccessFile(File file,String mode)
Creates a random access file stream from which to read and write (optional) to it.FileParameter.
RandomAccessFile(String name,String mode)
Creates a random access file stream to read from and write to (Optional). The file has the specified name.

ModeThe parameter specifies the access mode used to open the file. Allowed values and their meanings are:

Value

Meaning

"R" Open in read-only mode. AnyWriteMethods will throwIOException.
"Rw" Open for reading and writing. If the file does not exist, try to create it.
"Rws" Open for reading and writing,"Rw"Also, every update to the file content or metadata must be synchronized to the underlying storage device.
"Rwd" Open for reading and writing,"Rw"Also, every update to the file content is synchronized to the underlying storage device.
Write

Public static void RandomAccessFileDemo () throws IOException {// the file does not exist. It is created and exists. Do not create RandomAccessFile raf = new RandomAccessFile ("ran.txt", "rw "); // throw an exception. raf. write ("ASD ". getBytes (); // use the default Character Set of the platform to encode this String as a byte sequence and store the results in a new byte array. Raf. writeInt (97); // you can write basic data type bytes. int occupies 4 bytes and three spaces + araf. close ();}

Read and random read

Public static void read () throws IOException {RandomAccessFile raf = new RandomAccessFile ("ran.txt", "r"); byte [] by = new byte [6]; raf. read (by); String name = new String (by); int t = raf. readInt (); System. out. println ("name" + name); System. out. println ("t =" + t); raf. seek (2*7); // you can set the pointer position to read the System randomly. out. println ("pointer:" + raf. getFilePointer (); raf. close ();} public static void RandomAccessFileDemo () throws IOException {// the file does not exist. It is created and exists. Do not create RandomAccessFile raf = new RandomAccessFile ("ran.txt", "rw"); // throw an exception in raf. write ("Asad ". getBytes (); // use the default Character Set of the platform to encode this String as a byte sequence and store the results in a new byte array. Raf. writeInt (97); // you can write the basic data type bytes. int occupies 4 bytes and three spaces + araf. write ("Ade ". getBytes (); raf. writeInt (98); raf. close ();}

Random write and details


Public static void randomwrite () throws IOException {RandomAccessFile raf = new RandomAccessFile ("ran.txt", "rw"); // throw an exception/* raf. write ("Overwrite ". getBytes (); raf. write (102); raf. close (); // if you write directly, it overwrites the original ASA value */raf. seek (3*8); // write where you want to write, which means you can modify a value. // because some people have different words, but a maximum of 16 bytes of raf are supported. write ("Overwrite ". getBytes (); raf. write (102); raf. close (); // PS: Generally, multiple threads are used to write data to the file at the same time, controlling the information written to different locations by each thread (t1 thread writes data in [1-100] bytes, t2 thread write [101-200] bytes )}





Java deserialization error message: javaioStreamCorruptedException exception

I think it's a problem with the while statement. while (ois. readObject ()! = Null) This statement indicates that an object is read from the object stream. At this time, the object stream has read the byte sequence from the file and created an instance of the object. When you call ois. readObject () again in the while statement, the object stream will read the byte sequence in the file again to deserialize the object. If the object has reached EOF, the problem will occur. It seems that ObjectInputStream is not used in the while loop.
 
Deserialization of java objects

Import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. inputStream; import java. io. objectInput; import java. io. objectInputStream; import java. io. objectOutput; import java. io. objectOutputStream; import java. io. outputStream; import java. io. serializable; public class $ {public static void main (String [] args) {Bean bean = new Bean ("abcde", 20); String path = "D:/a.txt "; try {// write the file OutputStream OS = new FileOutputStream (path); ObjectOutput ow = new ObjectOutputStream (OS); ow. writeObject (bean); // read InputStream is = new FileInputStream (path); ObjectInput oi = new ObjectInputStream (is); Bean bean2 = (Bean) oi. readObject (); System. out. println (bean2.getName (); System. out. println (bean2.getAge ();} catch (Exception e) {e. printStackTrace () ;}} class Bean implements Serializable {private String name; private int age; public Bean (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}

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.