Created
July 5, 2017 07:40
-
-
Save hascode/497dd523f982eb630a8bbb0e47d5bc63 to your computer and use it in GitHub Desktop.
Java Externalizable Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hascode.sample; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.time.ZonedDateTime; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
User user = new User("Fred", ZonedDateTime.now()); | |
// serializing | |
try (FileOutputStream fos = new FileOutputStream( | |
"user.ser"); ObjectOutputStream outStream = new ObjectOutputStream(fos)) { | |
System.out.printf("serializing user: %s\n", user); | |
outStream.writeObject(user); | |
} | |
// deserializing | |
try (FileInputStream fis = new FileInputStream( | |
"user.ser"); ObjectInputStream in = new ObjectInputStream(fis)) { | |
User user1 = (User) in.readObject(); | |
System.out.printf("deserialized user: %s\n", user1); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hascode.sample; | |
import java.io.Externalizable; | |
import java.io.IOException; | |
import java.io.ObjectInput; | |
import java.io.ObjectOutput; | |
import java.time.ZonedDateTime; | |
public class User implements Externalizable { | |
private String name; | |
private ZonedDateTime birthday; | |
public User(){} | |
public User(String name, ZonedDateTime birthday) { | |
this.name = name; | |
this.birthday = birthday; | |
} | |
public String getName() { | |
return name; | |
} | |
public ZonedDateTime getBirthday() { | |
return birthday; | |
} | |
@Override | |
public String toString() { | |
final StringBuilder sb = new StringBuilder("User{"); | |
sb.append("name='").append(name).append('\''); | |
sb.append(", birthday=").append(birthday); | |
sb.append('}'); | |
return sb.toString(); | |
} | |
@Override | |
public void writeExternal(ObjectOutput out) throws IOException { | |
out.writeUTF(name); | |
out.writeObject(birthday); | |
} | |
@Override | |
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { | |
this.name = in.readUTF(); | |
this.birthday = (ZonedDateTime) in.readObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment