对象序列化
Posted mm163
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对象序列化相关的知识,希望对你有一定的参考价值。
1.对象
import java.io.Serializable; public class Dog implements Serializable { private String name; private int age; private String sex; public Dog(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } 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; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Dog{" + "name=‘" + name + ‘‘‘ + ", age=" + age + ", sex=‘" + sex + ‘‘‘ + ‘}‘; } }
2.对象序列化
import java.io.*; public class file { public static void main(String[] args) throws FileNotFoundException { in(); } private static void in(){ Dog dog = new Dog("11",2,"男"); File file = new File("F:/学习/1.txt"); try { OutputStream outputStream = new FileOutputStream(file); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(dog); objectOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
3.对象反序列化
import java.io.*; public class file { public static void main(String[] args) throws FileNotFoundException { out(); } private static void out(){ File file = new File("F:/学习/1.txt"); try { InputStream inputStream = new FileInputStream(file); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); Dog dog = (Dog)objectInputStream.readObject(); System.out.println(dog); objectInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
以上是关于对象序列化的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段12——JavaScript的Promise对象