Showing posts with label ObjectOutputStream. Show all posts
Showing posts with label ObjectOutputStream. Show all posts

Saturday, December 17, 2016

How to convert Map / Object to Bytes and save to internal storage and read back

package com.pkm;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author PRITOM
 */
public class MapObjectToByteArrayAndSaveToFile {
    public static void main(String[] args) throws Exception {
        Map<Integer, String> data = new HashMap<Integer, String>();
        data.put(1, "hello");
        data.put(2, "world");
        System.out.println(data.toString());
        store(data);
        data = (Map<Integer, String>) load();
        System.out.println(data.toString());
    }
    
    public static Object load() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("object.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        return objectInputStream.readObject();
    }
    
    public static void store(Object data) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("object.txt");
        ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(data);
        outputStream.close();
    }
}