Reliably convert any object to String and then back again

后端 未结 7 797
名媛妹妹
名媛妹妹 2020-12-02 13:35

Is there a reliable way to convert any object to a String and then back again to the same Object? I\'ve seen some examples of people converting them using toString()

7条回答
  •  一个人的身影
    2020-12-02 13:57

    Yes, it is Serialization You can use, ObjectInputStream.readObject and ObjectOutputStream.writeObject. Please see below example:

    MyClass myClass = new MyClass();
    FileOutputStream fileStream = new FileOutputStream("myObjectFile.txt");
    ObjectOutputStream os = new ObjectOutputStream(fileStream);
    os.writeObject(os);
    os.close();
    
    FileInputStream fileInStream = new FileInputStream("myObjectFile.txt");
    ObjectInputStream ois = new ObjectInputStream(fileInStream);
    MyClass myClass2 = ois.readObject();
    ois.close();
    

提交回复
热议问题