Java IO-5 序列化与反序列化流
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java IO-5 序列化与反序列化流相关的知识,希望对你有一定的参考价值。
建一个Person类
1 package demo05; 2 3 import java.io.Serializable; 4 5 public class Person implements Serializable { 6 private String name; 7 private int age; 8 //private transient int age; 阻止成员变量序列化 9 10 public Person(String name, int age) { 11 super(); 12 this.name = name; 13 this.age = age; 14 } 15 public Person() { 16 super(); 17 } 18 19 public String getName() { 20 return name; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 public int getAge() { 26 return age; 27 } 28 public void setAge(int age) { 29 this.age = age; 30 } 31 32 @Override 33 public String toString() { 34 return "Person [name=" + name + ", age=" + age + "]"; 35 } 36 37 }
1 package demo05; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.ObjectInputStream; 7 import java.io.ObjectOutputStream; 8 9 public class ObjectStreamDemo { 10 public static void main(String[] args) throws IOException, ClassNotFoundException { 11 func2(); 12 } 13 14 //ObjectOutputStream(OutputStream out) 15 public static void func1() throws IOException { 16 FileOutputStream out = new FileOutputStream("c:\\person.txt"); 17 ObjectOutputStream oos = new ObjectOutputStream(out); 18 Person p = new Person("lisi", 20); 19 oos.writeObject(p); 20 oos.close(); 21 } 22 23 public static void func2() throws IOException, ClassNotFoundException { 24 FileInputStream in = new FileInputStream("c:\\person.txt"); 25 ObjectInputStream ois = new ObjectInputStream(in); 26 Object obj = ois.readObject(); 27 System.out.println(obj); 28 ois.close(); 29 } 30 }
以上是关于Java IO-5 序列化与反序列化流的主要内容,如果未能解决你的问题,请参考以下文章