How to convert a card to bytes and save it to internal storage

How do I convert my Map<Integer, String> to byte[]and then write it to internal memory? I currently have:

        try {
            FileOutputStream fos = context.openFileOutput(Const.FILE_CATEGORIES, Context.MODE_PRIVATE);
            fos.write(null);
        } catch (FileNotFoundException e) {
            // reload and create the file again
        }

But .. I don’t know how to get Mapin the correct format and then decode it back to the original format as soon as I need to download it again. I need to recreate this file once a week and download it when the application starts.

+7
source share
3 answers
  • Using serialization in java, you can easily parse any serializable objects into a byte stream. Try using ObjectInputStream and ObjectOuputStream.

  • json . google-gson Java JSON .

  • Android. android.os.Parcel android (, ), . , , differenct .

, .

public static void main(String[] args) throws Exception {
    // Create raw data.
    Map<Integer, String> data = new HashMap<Integer, String>();
    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<Integer, String> data2 = (Map<Integer, String>) in.readObject();
    System.out.println(data2.toString());
}
+16

, , . , -. , . , , Java.

0

, , Google. 5 :

org.apache.commons.lang3.SerializationUtils, :

/**
 * Serialize the given object to a byte array.
 * @param object the object to serialize
 * @return an array of bytes representing the object in a portable fashion
 */
public static byte[] serialize(Object object);

/**
 * Deserialize the byte array into an object.
 * @param bytes a serialized object
 * @return the result of deserializing the bytes
 */
public static Object deserialize(byte[] bytes);
0

All Articles