从文件中读取和写入任何数据结构?

时间:2014-11-12 19:00:46

标签: java file data-structures objectinputstream objectoutputstream

下面是我用来读取和编写HashMaps的代码以及文件。我想知道,无论如何我可以重新考虑这个代码,以便可以读入和写出任何数据结构吗?而不是为每个数据结构创建一个新类?我感谢任何提供的帮助!

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 个答案:

答案 0 :(得分:2)

将writeOut()方法签名更改为

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

并在readIn(文件选择)中,使用Object temp代替HashMap<String, Object> temp

每当您使用readIn()时,您可能需要在执行未经检查的类型转换之前添加一些instanceof检查

答案 1 :(得分:2)

如果您想要任何Serializable Object,您可以执行类似的操作(另外,我会使用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);
    }
}

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