Skip to content

Instantly share code, notes, and snippets.

@MaksimDmitriev
Created May 15, 2016 16:14
Show Gist options
  • Save MaksimDmitriev/1808e3a7be43dffcba6d701b384b2eda to your computer and use it in GitHub Desktop.
Save MaksimDmitriev/1808e3a7be43dffcba6d701b384b2eda to your computer and use it in GitHub Desktop.
Enum Serialization
package etf;
public class A {
public int t;
A(int t) {
this.t = t;
}
}
package etf;
public enum E {
E1(new A(50)), E2(new A(100));
public A a;
E(A a) {
this.a = a;
}
}
package etf;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) {
E e = E.E1;
e.a.t = 2365;
E e11 = E.E1;
System.out.println(e11.a.t); // 2365 'cause there is only one instance of E1
write();
read();
}
private static void read() {
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(
"storage.txt"));
E e = (E) objectInputStream.readObject();
System.out.println(e.a.t); // 51 'cause there is only one instance of E2
} catch (IOException e) {
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void write() {
E e1 = E.E2;
e1.a.t = 51;
ObjectOutputStream objectOutputStream = null;
try {
FileOutputStream fileOutputStream = new FileOutputStream(
"storage.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(e1);
} catch (IOException e) {
} finally {
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment