Search code examples
javafiledata-structuresobjectinputstreamobjectoutputstream

Read and Write any data structure to and from a file?


Below is the code I use to read and write HashMaps too and from a file. I'm wondering, is there anyway I can re-factor this code so that any data structure can be read in and wrote out? Rather than creating a new class for each data structure? I appreciate any help offered!

public class FileHandler {

    static ObjectOutputStream oos;
    static ObjectInputStream ois;


    public static void writeOut(HashMap p, File selection) throws FileNotFoundException, IOException
      {
        oos = new ObjectOutputStream(new FileOutputStream(selection));
        oos.writeObject(p);
        oos.close();
      }

      public static HashMap<String, Object> readIn(File selection) throws FileNotFoundException, IOException, ClassNotFoundException
      {
          HashMap<String, Object> temp = null;
          ois = new ObjectInputStream(new FileInputStream(selection));
          temp = (HashMap<String, Object>) ois.readObject(); 
          ois.close();
        return temp;
      }


}

Solution

  • If you want any Serializable Object you could do something like (also, I would use try-with-resources),

    public static void writeOut(Object p, File selection)
            throws FileNotFoundException, IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(selection))) {
            oos.writeObject(p);
        }
    }
    

    and

    public static Object readIn(File selection) throws FileNotFoundException,
            IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                selection))) {
            return ois.readObject();
        }
    }