Java Learning lesson 56th-io Stream (10) object serialization and deserialization & Randomaccessfile

Source: Internet
Author: User
Tags modifiers object serialization serialization throw exception

Manipulating objects

ObjectInputStream, ObjectOutputStream

The object being manipulated needs to implement serializable (tag interface)

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

The default serialization mechanism for an object is written to the object's class, the class signature, and the values of non-transient and non-static fields. References to other objects (except transient and static fields) can also cause writing to those objects. Multiple references to a single object can be encoded using the reference sharing mechanism, which restores the object's graphics to the shape they were originally written to.

Serialization of objects

public static void Writeobj () throws IOException {//If it is a TXT file, it is a bunch of ... , the general suffix is objectobjectoutputstream oos = new ObjectOutputStream (New FileOutputStream ("Obj.object"));//Many frameworks are stored, Creation can be cumbersome, usually read oos.writeobject (new Perman ("a", 1)), or//simply store the object on the hard disk to prolong its life cycle oos.close ();//Complete the serialization of the object, The serialized object must implement serializable}

Note the WriteObject writes:

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


deserialization of an object

The purpose of the deposit is to read. FileInputStream can read the data of an object, but it cannot be spelled as an object

ObjectInputStream the basic data and objects previously written using ObjectOutputStream are deserialized.

In other words: ObjectInputStream can read only ObjectOutputStream write

ReadObject () Once, read an object

public static void Readobj () throws IOException, ClassNotFoundException {//If it is a TXT file, it is a bunch of ... , the general suffix is objectobjectinputstream ois = new ObjectInputStream (New FileInputStream ("Obj.object")); Perman p = (perman) ois.readobject ();//must throw exception System.out.println (p.getname () + ":" +p.getage ()); Ois.close ();}

Generally used for specific database connection objects, do not want to build, want to retain the object


About Serializable

The serialization runtime is associated with each serializable class using a version number called Serialversionuid, which is used during deserialization to verify that the sender and receiver of the serialized object have loaded a serialization-compatible class for the object.

Once the interface is implemented, the object is serialized with an ID number, and when the class changes (private int age:public int age), when read, it is judged whether the received class object (modified) is the same version as the class object being read (before the modification), and the exception is not thrown. Invalidclassexception, and the ID number is defined according to the class's characteristics and signature, which completes an ID number


Ps:serializable interface function: Used to add an ID to the serialized class and determine if the object is the same version


If the serializable class does not explicitly declare Serialversionuid, the serialization runtime calculates the default Serialversionuid value for the class based on the various aspects of the class, as described in the Java (TM) object serialization specification. However, it is strongly recommended that all serializable classes explicitly declare the SERIALVERSIONUID value because the calculation of the default Serialversionuid has a high sensitivity to the details of the class and may vary widely depending on the compiler implementation. This can result in an unexpected process during deserialization InvalidClassException . Therefore, to ensure consistency of serialversionuid values across different Java compilers, the serialization class must declare an explicit SERIALVERSIONUID value. It is also strongly recommended that private you use modifiers to display the declaration Serialversionuid, if possible, because this declaration applies only to the direct declaration class-The Serialversionuid field is not useful as an inherited member. An array class cannot declare an explicit serialversionuid, so they always have a default computed value, but the array class does not have a requirement to match the Serialversionuid value.


A serializable class can "serialVersionUID" long explicitly declare its own serialversionuid by declaring a field that is named (the field must be static (static), eventually (final)):

Any-access-modifier static final Long serialversionuid = 42L;
Arbitrary access modifiers

Class Perman implements Serializable{private static final long serialversionuid = 845645641123231l;//Blind Write +l//If the object wants to serialize, You must implement the interface, tag private String name;private int age;//...} public static void Readobj () throws IOException, ClassNotFoundException {//If it is a TXT file, it is a bunch of ... , the general suffix is objectobjectinputstream ois = new ObjectInputStream (New FileInputStream ("Obj.object")); Perman p = (perman) ois.readobject ();//must throw exception System.out.println (p.getname () + ":" +p.getage ()); Ois.close ();}


After this modification, the class change is not a problem, because the ID number is not changed, can still be read out, stored objects


Keyword transient (temporary)

When writing to an object, some data in the object does not want to be written like a hard disk, using that 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 IO packages:

Randomaccessfile: Random access to the file, its own method of reading and writing.

by skipbytes (int x), seek (int x) to achieve random access.

Pipe flow: PipedInputStream and PipedOutputStream

The input and output can be connected directly by using the collection thread


Randomaccessfile

is not a subclass in the IO system.

Characteristics:

1. Able to read and write

2. The memory in this object maintains an array that can manipulate the elements in the array by pointers

3. You can get the position of the pointer through the Getfilepointer method, set the position of the pointer by the Seek method

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

5. Limitations, as can be seen from the constructor, sources and sinks can only be files

Instances of this class support read and write to random -access files . Random access to a file behaves like a large byte array stored in the file system. There is a cursor or index that points to the suppressed array, called a file pointer , and the input operation reads the bytes from the file pointer and moves the file pointer forward as the byte is read. If the random Access file is created in read/write mode, the output operation is also available, and the output operation starts writing bytes from the file pointer and moves the file pointer forward as it writes to the byte. Writing an output operation after the current end of the suppressed array causes the array to expand. The file pointer can be getFilePointer read through the method and seek set through the method.

Construction Method Summary
RandomAccessFile(File file,String mode)
Creates a random-access file stream from which to read and write (optionally), which is specified by the File parameter.
RandomAccessFile(String name,String mode)
Creates a random-access file stream from which to read and write (optionally) a file with the specified name.

The mode parameter specifies the access pattern used to open the file. The allowed values and their meanings are:

meaning

" R " The write method that invokes the resulting object will cause the IOException to be thrown.
"RW" open for read and write. If the file does not already exist, try to create the file.
"RWS" open for read and write, and for RW , also requires that each update to the contents or metadata of the file be synchronously written to the underlying storage device.
"RWD" open for read and write, and for RW , also requires that each update to the file contents be synchronously written to the underlying storage device.  
Write

public static void Randomaccessfiledemo () throws IOException {//File not present, created, present, not created randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "RW");//Throw Abnormal raf.write ("ASD". GetBytes ());//Use the default character set of the platform to encode this String as a byte sequence and store the result in a new The byte array. Raf.writeint (97);//can write basic data type Byte, int accounts for 4 bytes  three spaces +araf.close ();}

Read and Random Read

public static void Read () throws IOException {Randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "R"); byte[] by = new B Yte[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);//Set the position of the pointer, you can implement a random read System.out.println ("pointer:" +raf.getfilepointer ()) ; Raf.close ();} public static void Randomaccessfiledemo () throws IOException {//File not present, created, present, not created randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "RW");//Throw abnormal raf.write ("Assad". GetBytes ());//Use the default character set of the platform to encode this String as a byte sequence and store the result in a new The byte array. Raf.writeint (97);//can write basic data type Byte, int accounts for 4 bytes  three spaces +araf.write ("Adelaide". GetBytes ()); Raf.writeint (98); Raf.close ();}

Random writes and details


public static void Randomwrite () throws Ioexception{randomaccessfile RAF = new Randomaccessfile ("Ran.txt", "RW");//Throw exception */ Raf.write ("Overwrite". GetBytes ()); Raf.write (102); Raf.close ();//If you write directly, it will overwrite the value of the original     ASA */raf.seek (3*8);//write on where you want to go, It also means that you can modify a value//because some names have different words, but up to 16 bytes raf.write ("Overwrite". GetBytes ()); Raf.write (102); Raf.close ();// PS: It is generally a collection of multiple threads simultaneously writing data to a file, controlling the information that each thread writes to a different location (T1 thread writes [1-100] bytes, T2 thread writes [101-200] bytes)}




Java Learning lesson 56th-io Stream (10) object serialization and deserialization & Randomaccessfile

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.