java serializable

1. Implement Serializable data class

class Person implements Serializable {
private String name = "Tom";
private int age = 16;
public Person () {

}
public Person(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;
}

@Override
public String toString() {
	return "Person [name=" + name + ", age=" + age + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
			+ ", toString()=" + super.toString() + "]";
}
}

2. Decide the file output destination

private static String filename = String.format("D:%s99_temp%sseri", File.separator,File.separator);

3. Serialize

private static void serializable (Person person ) {
	try {
		ObjectOutputStream oOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
		oOutputStream.writeObject(person);
		oOutputStream.close();
	} catch (FileNotFoundException e) {

// TODO auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO auto-generated catch block e.printStackTrace(); } }

4. Anti-serialize, (make the retained file an object)

private static void deserializable() {
	try {
		ObjectInputStream oInputStream = new ObjectInputStream(new FileInputStream(filename));
		Person person = (Person) oInputStream.readObject();
		System.out.println(person.toString());
		oInputStream.close();
	} catch (ClassNotFoundException e) {

// TODO auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO auto-generated catch block e.printStackTrace(); } }

5. Test

public static void main(String[] args) {
	serializable(new Person());
	deserializable();
}

6. Summary

No. Class used, interface Remarks
1.Data class inheritance Serializable Serialize
3.Serialize ObjectOutputStream Export object
3.Serialize FileOutputStream Export file
4.Anti-serialize ObjectInputStream Loading an object
4.Anti-serialize FileInputStream Read file

Sample code

Recommended Posts

java serializable
Java
Java
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
java (override)
java (method)
Java Day 2018
Java string
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
[Java] Array
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
Java inheritance
[Java] Overload
Java basics
[Java] Annotation
java beginner
Java (add2)
JAVA (Map)
Java9 collection
Java basics
Java diary
Java inheritance
[Java] enum
Java array
Java (add)
Java method
Java (remove)
JAVA memorandum