import java.io.*;
/**
* @author lzy
*/
public class Main {
public static void main(String[] args) {
Person xiaoming = new Person(18, "小明");
File file = new File("src\\file\\1.txt");
File fileParent = file.getParentFile();
//如果父级文件夹不存在,就创建
if (!fileParent.exists()) {
fileParent.mkdirs();
}
//序列化对象
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) {
//创建文件
file.createNewFile();
objectOutputStream.writeObject(xiaoming);
objectOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
//反序列化
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
Person person = (Person) objectInputStream.readObject();
System.out.println(person);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Person implements Serializable {
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
JAVA序列化对象到文件、反序列化
最新推荐文章于 2023-06-04 11:47:13 发布