有一段程序用objectOutputStream的writeobject()方法连续向文件dict.dic中写入了5个Book类型的对象。现请你写一段程序将这5个对象读出来。
时间: 2024-02-20 22:01:49 浏览: 69
可以使用ObjectInputStream的readObject()方法来读取这5个Book对象,具体代码如下:
```java
import java.io.*;
public class ReadObjects {
public static void main(String[] args) throws IOException, ClassNotFoundException {
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);
}
ois.close();
fis.close();
}
}
```
其中,Book类需要实现Serializable接口,以便可以序列化和反序列化:
```java
import java.io.Serializable;
public class Book implements Serializable {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getPages() {
return pages;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", pages=" + pages +
'}';
}
}
```
注意,在读取对象时,需要使用强制类型转换将Object类型转换为Book类型。同时,需要注意读取的顺序与写入的顺序应该一致,否则读取出来的对象可能会出现错误。
阅读全文