从Java中的二进制文件读取序列化的对象? [英] Reading serialized objects from a binary file in java?

查看:349
本文介绍了从Java中的二进制文件读取序列化的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题。

如何读取java中二进制文件的所有内容?



我写了一些代码,检索第一个对象。

这是我的代码:

pre $ Object $ in = new ObjectInputStream(new FileInputStream(C:\\Users\\فاطمة\\Downloads \\student.bin));
Binary b2 =(Binary)in.readObject();
System.out.println(Student ID:+ b2.id);
System.out.println(Student Name:+ b2.name);
System.out.println(Student Grade:+ b2.grade);
in.close();


解决方案

如果您无法访问生成该文件的代码,则可能有两种情况:

(b>


  • )或者你知道对象的数量,那么你可以做正确数量的 ObjectInputStream.readObject()调用,最好使用作为循环

  • ,否则,问题是检测到文件。你可以使用,而循环加上 try / catch(EOFException)

I have a simple question.

How to read all the contents of the binary file in java ?

I wrote some code but it only retrieves the first object.

Here is my code:

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\فاطمة\\Downloads\\student.bin"));
    Binary b2 = (Binary)in.readObject();
    System.out.println("Student ID: " + b2.id);
    System.out.println("Student Name: " + b2.name);
    System.out.println("Student Grade: " + b2.grade);
    in.close();

解决方案

As malinator mentionned, it is bad practice to concatenate serialized objects in a single file, they should be contained in a Collection.

If you do not have access to the code producing the file, there can be 2 situations :

  • either you know the number of objects, then you can do the right number of ObjectInputStream.readObject() calls, preferably with a for loop
  • or you don't, then the problem is detecting the end of the file. You could use a while loop coupled with a try/catch(EOFException).

这篇关于从Java中的二进制文件读取序列化的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆