Usage of Externalizable interface

xiaoxiao2021-03-06  69

The Externalizable interface inherits the serializable interface to serialize the required object information when serialization. The Externalizable interface provides two ways: WriteExternal (ObjectOut out) and readExternal (ObjectInput IN) implement these two methods in the serialized classes, which will be automatically performed automatically when such serialization. Use to customize such. For example: if you need serialization of a class Test: import java.io. *;

class Test implements Externalizable {// Test class must implement the interface Externalizable private String letterstates = "fanruijun"; private int num = 0; public Test () {} public void writeExternal (ObjectOutput out) throws IOException {out.writeObject (letterstates); Out.write (88); // In serialized data last added 88}

public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException {letterstates = (String) in.readObject (); num = in.read (); // add to the mix digital 88} public void putOut () {// Test System. Out.println (Letterstates Num);}} Serialized TEST Class: Apptest Import Java.io. *;

Public class appteest {

private void saveGame () {Test m = new Test (); if (m = null!) {try {FileOutputStream ostream = new FileOutputStream ( "t.txt"); ObjectOutputStream p = new ObjectOutputStream (ostream); p.writeObject ( m); // WriteExternal () automatically executes p.flush (); {System.close ();} catch (ioException ie) {system.out.println ("Error Saving File:"); System.Out.println (IOE .getMessage ());}}} private void loadGame () {try {FileInputStream instream = new FileInputStream ( "t.txt"); ObjectInputStream p = new ObjectInputStream (instream); Test m = (Test) p.readObject () ; // readexternal () Automated execution M.PUTOUT (); instream.close ();} catch (exception e) {system.out.println ("error loading file:"); system.out.println (E.GetMessage ());}} public static Void main (String [] args) {new apptest (). savegame (); new apptest (). LoadGame ();}} Run Results: D: / Test / Basic> Javac Apptest.java D: / Test / Basic> Javac Test.javad: / Test / Basic> Java ApptestFanruijun88

转载请注明原文地址:https://www.9cbs.com/read-108383.html

New Post(0)