0

I use IDEA to generate a file, and serialize the object in the file, but no matter what encoding format is set, the final content is gibber code enter image description here I've tried all kinds of coding, and I still end up with gibberish

enter image description here

I've tried many common coding formats

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();
    }
}

I want the open file to display properly

Eagle
  • 3
  • 3
  • 3
    That's to be expected. Java serialization does not output text. If you want something human readable you'll need to use something like JSON or XML. There are libraries out there that help with the conversion between Java objects and those file formats. – Slaw May 10 '19 at 14:06
  • Let me try@Slaw – Eagle May 10 '19 at 14:34

1 Answers1

2

When Java serializes an object, it creates raw byte data. It may not be human readable, but it can be deserialized into the object by any other JVM instance.

If you need to serialize the object into something that is more human readable or compatible with other software components, I'd recommend serializing into JSON or XML.

For JSON, I recommend using Gson.

For XML, refer to this SO answer.

michael
  • 463
  • 3
  • 9