有一段程序用objectOutputStream的writeobject()方法连续向文件dict.dic中写入了5个Book类型的对象。现请你写一段程序将这5个对象读出来。 注意:你的程序中要把Person和Book类的定义复制过去。
时间: 2024-02-18 15:59:43 浏览: 54
以下是示例代码:
```java
import java.io.*;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String title;
private String author;
private int year;
public Book(String title, String author, int year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "Book [title=" + title + ", author=" + author + ", year=" + year + "]";
}
}
public class ReadObjects {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("dict.dic");
ObjectInputStream ois = new ObjectInputStream(fis);
for (int i = 0; i < 5; i++) {
Book book = (Book) ois.readObject();
System.out.println(book.toString());
}
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们定义了两个类:`Person`和`Book`。这两个类都实现了`Serializable`接口,这样它们的对象就可以被序列化和反序列化。
然后,在`ReadObjects`类中,我们创建了一个`FileInputStream`对象,用于读取`dict.dic`文件。接着,我们创建了一个`ObjectInputStream`对象,并使用它的`readObject()`方法连续读取了5个`Book`对象,并打印了每个对象的信息。
注意:在使用`ObjectOutputStream`的`writeObject()`方法写入对象时,对象的类必须实现`Serializable`接口。否则,会抛出`NotSerializableException`异常。
阅读全文