De-serializing objects from a file in Java

瘦欲@ 提交于 2019-12-28 16:11:32

问题


I have a file which contains multiple serialized objects of class XYZ. While serializing, the each XYZ object was appended to the file.

Now I need to read each object from the file, and I am able to read only the first object.

Any idea how I can read each object from the file and eventually store it into a List?


回答1:


Try the following:

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

Following up on Tom's brilliant comment, the solution for multiple ObjectOutputStreams would be,

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



回答2:


You can't append ObjectOutputStreams to a file. They contain headers as well as the objects you wrote. Revise your technique.

Also your EOF detection is wrong. You should catch EOFException separately. OptionalDataException means something different entirely.




回答3:


this works for me

  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:


You can follow the below mentioned code for handling end of file differently:

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

}

It will write and read multiple integer objects from the file without throwing any exception.



来源:https://stackoverflow.com/questions/7826834/de-serializing-objects-from-a-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!