2020.8.5第三十天

1.今天学习对象序列化与反序列化

序列化

将实体类标注为可以序列化

 1 import java.io.Serializable;
 2 public class Person implements Serializable{
 3 private String name;
 4 private int age;
 5 public String getName() {
 6 return name;
 7 }
 8 public void setName(String name) {
 9 this.name= name;
10 }
11 public int getAge(){
12 return age;
13 }
14 public void setAge(int age){
15 this.age = age;
16 }
17 public String toString(){
18     return "姓名: "+name+",年龄"+age;
19 }
20 }

写到文件中

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 import java.io.ObjectOutputStream;
 4 public class ObjectoutputstreamDemo{
 5 public static void main(String[] args) throws IOException{
 6 ObjectOutputStream oos= new ObjectOutputStream (
 7 new FileOutputStream (
 8 "D:/Hello.txt"));
 9 Person p= new Person();
10 p.setAge (20);
11 p.setName("伍正云");
12 oos.writeObject(p);
13 oos.close();
14 }
15 }

反序列化

 1 import java.io.FileInputStream;
 2 import java.io.IOException;
 3 import java.io.ObjectInputStream;
 4 public class objectInputStrearmDemo{
 5 public static void main (String[] args) throws IOException,
 6 ClassNotFoundException {
 7 ObjectInputStream ois =new ObjectInputStream (
 8 new FileInputStream(
 9 "D:/Hello.txt"));
10 Person p= (Person) ois.readObject();
11 ois.close();
12 System.out.println (p);
13 }
14 }

 

 transient关键字

public class Person implements Serializable{
private transient String name;
private int age;
. . .
}

序列化一组对象

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 import java.io.ObjectOutputStream;
 4 public class objectoutputstreamDemo2{
 5 public static void main (String[]args) throws IOException{
 6 ObjectOutputStream oos =new ObjectOutputStream(
 7 new FileOutputStream(
 8 "D:/Hello.txt"));
 9 Person p= new Person();
10 p.setAge(20);
11 p.setName("伍正云");
12 Person p2=new Person();
13 p.setAge(20);
14 p.setName("伍正云22");
15 Person[] ps= {p,p2};
16 oos.writeObject(ps);
17 oos.close();
18 }
19 }

2.序列化的数据存到文件里变成乱码

3.明天继续学习第12章.

 

posted @ 2020-08-05 13:13  敲敲代代码码  阅读(113)  评论(0编辑  收藏  举报