首页 > 解决方案 > 我用IDEA把对象序列化成文件,但是不管我设置什么格式,打开的文件都是乱码

问题描述

我用IDEA生成文件,对文件中的对象进行序列化,但是不管设置什么编码格式,最终的内容都是乱码在这里输入图片描述各种编码都试过了,最后还是胡言乱语

在此处输入图像描述

我尝试了许多常见的编码格式

public class Student implements Serializable{
    private String a1;
    private String a2;

    public Student(){

    }

    public Student(String a1, String a2) {
        this.a1 = a1;
        this.a2 = a2;
    }

    public String getA1() {
        return a1;
    }

    public void setA1(String a1) {
        this.a1 = a1;
    }

    public String getA2() {
        return a2;
    }

    public void setA2(String a2) {
        this.a2 = a2;
    }
}

public class ObjectSeria {

    public static void main(String[] args) throws Exception{
        File file = new File("demo.txt");
        ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(file)
        );
        Student student = new Student("a","b");
        oos.writeObject(student);
        oos.flush();
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(file)
        );
        Student student1 = (Student)ois.readObject();
        System.out.println(student1);
        ois.close();
    }
}

我希望打开的文件正确显示

标签: java

解决方案


当 Java 序列化一个对象时,它会创建原始字节数据。它可能不是人类可读的,但它可以被任何其他 JVM 实例反序列化为对象。

如果您需要将对象序列化为更易于阅读或与其他软件组件兼容的东西,我建议您序列化为 JSON 或 XML。

对于 JSON,我建议使用Gson

对于 XML,请参阅SO 答案。


推荐阅读