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

360 views Asked by At

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;
      }


}
2

There are 2 answers

0
Elliott Frisch On BEST ANSWER

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();
    }
}
0
TubaBen On

Change writeOut() method signature to

public static void writeOut(Serializable o, File selection) throws FileNotFoundException

and in readIn(File selection), use Object temp instead of HashMap<String, Object> temp

You might want to add some instanceof checks before doing an unchecked type conversion whenever you use readIn()