【问题标题】:Read and Write any data structure to and from a file?从文件中读取和写入任何数据结构?
【发布时间】:2015-01-09 17:59:23
【问题描述】:

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

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


}

【问题讨论】:

    标签: java file data-structures objectinputstream objectoutputstream


    【解决方案1】:

    如果你想要任何可序列化的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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      将 writeOut() 方法签名更改为

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

      在 readIn(文件选择)中,使用 Object temp 而不是 HashMap&lt;String, Object&gt; temp

      您可能希望在使用 readIn() 进行未经检查的类型转换之前添加一些 instanceof 检查

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-30
        • 2021-10-12
        相关资源
        最近更新 更多