【问题标题】:De-serializing objects from a file in Java从Java文件中反序列化对象
【发布时间】:2011-10-19 19:16:18
【问题描述】:

我有一个文件,其中包含多个 XYZ 类的序列化对象。序列化时,每个 XYZ 对象都附加到文件中。

现在我需要从文件中读取每个对象,并且我只能读取第一个对象。

知道如何从文件中读取每个对象并最终将其存储到列表中吗?

【问题讨论】:

  • 能否提供一个代码 sn-p 来说明问题?
  • 所有对象是在单个会话中编写的(带有单个 ObjectOutputStream 实例),还是存在多个会话(为每个会话创建、使用和关闭 ObjectOutputStream)?

标签: java serialization deserialization


【解决方案1】:

尝试以下方法:

List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream("cool_file.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);

try {
    while (true) {
        results.add(ois.readObject());
    }
} catch (OptionalDataException e) {
    if (!e.eof) 
        throw e;
} finally {
    ois.close();
}

根据 Tom 的精彩评论,多个ObjectOutputStreams 的解决方案是,

public static final String FILENAME = "cool_file.tmp";

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String test = "This will work if the objects were written with a single ObjectOutputStream. " +
            "If several ObjectOutputStreams were used to write to the same file in succession, " +
            "it will not. – Tom Anderson 4 mins ago";

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(FILENAME);
        for (String s : test.split("\\s+")) {
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s);
        }
    } finally {
        if (fos != null)
            fos.close();
    }

    List<Object> results = new ArrayList<Object>();

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(FILENAME);
        while (true) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            results.add(ois.readObject());
        }
    } catch (EOFException ignored) {
        // as expected
    } finally {
        if (fis != null)
            fis.close();
    }
    System.out.println("results = " + results);
}

【讨论】:

  • 如果对象是用单个ObjectOutputStream 编写的,这将起作用。如果多个ObjectOutputStreams被连续写入同一个文件,则不会。
  • @TomAnderson 如此真实......好吧,修复了。
  • 我们实际上还不知道这些对象是单独编写的。您的第一个答案可能完全正确!
  • 我不知道过去 4 年是否发生了一些变化,但当我尝试使用多个 ObjectOutputStreams 时,它对我有用。每次我写入文件时,我都会确保我正在附加,例如:fos = new FileOutputStream(FILENAME, true);
【解决方案2】:

您不能将 ObjectOutputStreams 附加到文件中。它们包含标题以及您编写的对象。修改你的技术。

您的 EOF 检测也是错误的。您应该单独捕获 EOFException 。 OptionalDataException 意味着完全不同的东西。

【讨论】:

    【解决方案3】:

    这对我有用

      System.out.println("Nombre del archivo ?");
                      nArchivo= sc.next();
                      sc.nextLine();
                      arreglo=new ArrayList<SuperHeroe>();
    
                      try{
    
                             FileInputStream fileIn = new FileInputStream(nArchivo);
                             ObjectInputStream in = new ObjectInputStream(fileIn);
    
                            while(true){
                                arreglo.add((SuperHeroe) in.readObject());
    
                            }
    
    
    
                        }
    
                          catch(IOException i)
                          {
                             System.out.println("no hay mas elementos\n elementos cargados desde el archivo:" );
    
                             for(int w=0;w<arreglo.size();w++){
                              System.out.println(arreglo.get(w).toString());
                             }
    
    
    
                          }catch(ClassNotFoundException c)
                          {
                             System.out.println("No encontre la clase Estudiante !");
                             c.printStackTrace();
    
                             return;
                          }  
    

    【讨论】:

      【解决方案4】:

      您可以按照下面提到的代码以不同方式处理文件结尾:

      public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
          // TODO Auto-generated method stub
      
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E://sample.txt"));
          oos.writeObject(new Integer(5));
          oos.writeObject(new Integer(6));
          oos.writeObject(new Integer(7));
          oos.writeObject(new Integer(8));
          oos.flush();
          oos.close();
      
          ObjectInputStream ios = new ObjectInputStream(new FileInputStream("E://sample.txt"));
          Integer temp;
          try {
              while ((temp = (Integer) ios.readObject()) != null) {
                  System.out.println(temp);
              }
          } catch (EOFException e) {
      
          } finally {
              ios.close();
          }
      
      }
      

      它将从文件中写入和读取多个整数对象,而不会抛出任何异常。

      【讨论】:

        猜你喜欢
        • 2013-01-23
        • 1970-01-01
        • 2021-10-01
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多