How to convert Map to Bytes and save to internal storage

前端 未结 3 1584
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 17:09

How can I convert my Map> to byte[], and then write it to internal storage? I currently have:

        try {
                 


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 17:51

    1. Using serialization in java you can easily parse any serializable objects to byte stream. Try to use the ObjectInputStream and the ObjectOuputStream.

    2. Use json to restore. You can use google-gson to convert Java objects to JSON and vice-versa.

    3. Use Parcel in android. The class android.os.Parcel is designd to pass data between the components in android(activity, service), but you can still use it to do data persistence. Just remember do not send the data to internet since differenct platforms may have different algorithm to do parsing.

    I wrote a demo for serialization , have a try.

    public static void main(String[] args) throws Exception {
        // Create raw data.
        Map data = new HashMap();
        data.put(1, "hello");
        data.put(2, "world");
        System.out.println(data.toString());
    
        // Convert Map to byte array
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(data);
    
        // Parse byte array to Map
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        Map data2 = (Map) in.readObject();
        System.out.println(data2.toString());
    }
    

提交回复
热议问题