• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于java:Java-中序列化与反序列化看这篇就够了

java 搞代码 4年前 (2022-01-28) 29次浏览 已收录 0个评论

/**

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

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 Fi<em style="color:transparent">来源[email protected]搞@^&代*@码网</em>leOutputStream(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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于java:Java-中序列化与反序列化看这篇就够了
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址