serialize java object to text file

后端 未结 2 861
半阙折子戏
半阙折子戏 2021-01-27 01:49

I have a java library, I would like to save an instance of a java object to a text file. I have tried to use all java libraries for serialization and deserialization to xml:

相关标签:
2条回答
  • 2021-01-27 02:28

    The easiest way is probably to use the native Java serialization. It will generate a binary representation of the object, but you can encode the generated byte array with Base64 to transform it to text:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(myObject);
    oos.flush();
    byte[] binary = baos.toByteArray();
    String text = Base64.encodeBase64String(binary); // Base64 is in the apache commons codec library
    // save text to a file
    

    Note that the object, and every object it references (recursively) must implement java.io.Serializable for this to work.

    0 讨论(0)
  • 2021-01-27 02:44

    You can use Gson to convert java object to Json and vice versa

    Here is example from the Gson user guide.

    Or may be apache digester can help.

    0 讨论(0)
提交回复
热议问题