Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3657245
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Java

2021-06-18 17:13:26

/**

 * 实现了序列化接口的学生类

 */

public class Student implements Serializable {

    private String name;

    private char sex;

    private int year;

    private double gpa;

    public Student() {

    }

    public Student(String name,char sex,int year,double gpa) {

        this.name = name;

        this.sex = sex;

        this.year = year;

        this.gpa = gpa;

    }

    public void setName(String name) {

        this.name = name;

    }

    public void setSex(char sex) {

        this.sex = sex;

    }

    public void setYear(int year) {

        this.year = year;

    }

    public void setGpa(double gpa) {

        this.gpa = gpa;

    }

    public String getName() {

        return this.name;

    }

    public char getSex() {

        return this.sex;

    }

    public int getYear() {

        return this.year;

    }

    public double getGpa() {

        return this.gpa;

    }

}

Student类的对象序列化到文件/Users/sschen/Documents/student.txt,并从该文件中反序列化,向console显示结果。代码如下:

public class UserStudent {

    public static void main(String[] args) {

        Student st = new Student("Tom",'M',20,3.6);

        File file = new File("/Users/sschen/Documents/student.txt");

        try {

            file.createNewFile();

        }

        catch(IOException e) {

            e.printStackTrace();

        }

        try {

            //Student对象序列化过程

            FileOutputStream fos = new FileOutputStream(file);

            ObjectOutputStream oos = new ObjectOutputStream(fos);

            oos.writeObject(st);

            oos.flush();

            oos.close();

            fos.close();

            //Student对象反序列化过程

            FileInputStream fis = new FileInputStream(file);

            ObjectInputStream ois = new ObjectInputStream(fis);

            Student st1 = (Student) ois.readObject();

            System.out.println("name = " + st1.getName());

            System.out.println("sex = " + st1.getSex());

            System.out.println("year = " + st1.getYear());

            System.out.println("gpa = " + st1.getGpa());

            ois.close();

            fis.close();

        }

        catch(ClassNotFoundException e) {

            e.printStackTrace();

        }

        catch (IOException e) {

            e.printStackTrace();

        }

    }

}

而查看文件/Users/sschen/Documents/student.txt,其内保存的内容并不是可以容易阅读的内容:

aced 0005 7372 001f 636f 6d2e 7373 6368

656e 2e53 6572 6961 6c69 7a61 626c 652e

5374 7564 656e 74f1 5dbd a4a0 3472 4d02

0004 4400 0367 7061 4300 0373 6578 4900

0479 6561 724c 0004 6e61 6d65 7400 124c

6a61 7661 2f6c 616e 672f 5374 7269 6e67

3b78 7040 0ccc cccc cccc cd00 4d00 0000

1474 0003 546f 6d

阅读(1198) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~