码迷,mamicode.com
首页 > 编程语言 > 详细

Java IO-5 序列化与反序列化流

时间:2017-05-30 16:02:47      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:ansi   dem   cto   write   obj   pack   setname   private   ide   

建一个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 序列化与反序列化流

标签:ansi   dem   cto   write   obj   pack   setname   private   ide   

原文地址:http://www.cnblogs.com/lwn007/p/6920330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!