IODemo
package com.jsu.Demo;
import java.io.*;
public class IODemo {
public static void main(String[] args) {
Student student = new Student("ZHANGS",1001);
try {
SerializableObjectUtils.SerializeObject("D://兵马俑", student);
} catch (IOException e) {
e.printStackTrace();
}
try {
Object o = SerializableObjectUtils.reSerializableObject("D://兵马俑");
student = (Student) o;
System.out.println(student.getName());
student.setAge(2000);
System.out.println(student.getAge());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
SerializableObjectUtils
package com.jsu.Demo;
import java.io.*;
public class SerializableObjectUtils {
public static void SerializeObject(String destPath, Object obj) throws IOException{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
fos = new FileOutputStream(destPath);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
}
public static Object reSerializableObject(String srcPath) throws IOException, ClassNotFoundException{
FileInputStream fis = null;
ObjectInputStream ois = null;
fis = new FileInputStream(srcPath);
ois = new ObjectInputStream(fis);
Object o = ois.readObject();
ois.close();
fis.close();
return o;
}
// public static void copy(String Src,String Address){
// File src = new File(Src);
// File address = new File(Address);
//
// }
}
Student
package com.jsu.Demo;
import java.io.Serializable;
import java.util.Objects;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
// private int id;
private String name;
private int age;
public Student() {
}
// public Student(int id, String name) {
// this.id = id;
// this.name = name;
// }
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// public int getId() {
// return id;
// }
// @Override
// public boolean equals(Object o) {
// if(this == o) {
// return true;
// }
// if(o == null || getClass() != o.getClass()) {
// return false;
// }
// Student student = (Student) o;
// return id == student.id && Objects.equals(name, student.name);
// }
//
// @Override
// public int hashCode() {
// retuen Objects.hash(id.name);
// }
// public void setId(int id) {
// this.id = id;
// }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
运行后会发现D盘中多了一个“兵马俑”的文件,实际上这篇文件经历了序列化和反序列化的过程,其中的数据经历过一次改变。