在 Java 中从文件中反序列化对象

发布于 2024-12-11 03:49:22 字数 130 浏览 0 评论 0原文

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

初见终念 2024-12-18 03:49:22

尝试以下操作:

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 的精彩评论,多个 ObjectOutputStream 的解决方案是,

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

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);
}
呆° 2024-12-18 03:49:22

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

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

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.

冷…雨湿花 2024-12-18 03:49:22

这对我有用

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

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;
                      }  
最美不过初阳 2024-12-18 03:49:22

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

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

}

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文