反序列化Java中的许多对象? [英] Deserialize many objects in java?

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

问题描述

我有一个问题.现在我将许多对象序列化为一个名为student.bin的二进制文件

I have a question. now i serialize many objects in a binary file called student.bin

在将对象数据添加到二进制文件中之后,现在我要检索写入二进制文件中的所有数据.

after adding object data in the binary file now i want to retrieve all the data written in the binary file.

但是它只检索第一个对象数据.

but it only retrieve the first object data.

问题是:如何获取文件的所有内容?

the question is: how to get all contents of the file?

这是我的代码:

import java.util.Scanner;
import java.io.*;
import java.io.Serializable;

public class Binary implements Serializable{

public int id;
public String name;
public int grade;

public static void main(String argv[]) throws IOException, ClassNotFoundException
{
    Binary b = new Binary();
    Scanner sc = new Scanner(System.in);
    System.out.printf("Enter student id: ");
    b.id = sc.nextInt();
    System.out.printf("Enter student name: ");
    b.name = sc.next();
    System.out.printf("Enter student grade: ");
    b.grade = sc.nextInt();
    ObjectOutputStream bin = new ObjectOutputStream(new FileOutputStream("C:\\Users\\فاطمة\\Downloads\\student.bin",true));
    bin.writeObject(b);
    bin.close();

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

}
}

推荐答案

使用while循环.流具有 hasNext 方法,只要文件中有未读的字节,该方法就可以让您继续读取对象.请注意,如果文件末尾有多余的字节,则会导致错误.

Use a while loop. Streams have a hasNext method which will let you keep reading objects as long as there are unread bytes in the file. Note that if the file has extra bytes at the end, this will cause an error.

List<Binary> binaries = new ArrayList<Binary>();
while(in.hasNext()) {
    binaries.add((Binary) in.readObject());
}

如果这无效,我深表歉意,我现在无权对其进行测试.

I apologise if this is invalid, I don't have access to test it right now.

hasNext 可能是Scanner而不是Stream的一种方法,在这种情况下,您必须将Stream包裹在Scanner对象中: Scanner read = new Scanner(in).

It's possible hasNext is a method of Scanner rather than Stream, in which case you'd have to wrap the Stream in a Scanner object: Scanner read = new Scanner(in).

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

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