创建Book类,成员属性有:书号、书名、作者、价格、出版社、出版年份。 创建该类的10个对象。(4)将这10个对象按对象存入文件中并读出到一List集合中。用java实现
时间: 2024-05-07 21:16:49 浏览: 179
好的,让我来回答你的问题。
首先我们需要定义一个Book类:
```java
public class Book implements Serializable {
private String bookNumber;
private String bookName;
private String author;
private double price;
private String publisher;
private int publishYear;
// getter and setter methods
@Override
public String toString() {
return "Book{" +
"bookNumber='" + bookNumber + '\'' +
", bookName='" + bookName + '\'' +
", author='" + author + '\'' +
", price=" + price +
", publisher='" + publisher + '\'' +
", publishYear=" + publishYear +
'}';
}
}
```
然后我们可以创建10个Book对象并设置它们的属性:
```java
Book book1 = new Book();
book1.setBookNumber("001");
book1.setBookName("Java编程思想");
book1.setAuthor("Bruce Eckel");
book1.setPrice(79.9);
book1.setPublisher("机械工业出版社");
book1.setPublishYear(2007);
Book book2 = new Book();
book2.setBookNumber("002");
book2.setBookName("Java核心技术");
book2.setAuthor("Cay S. Horstmann、Gary Cornell");
book2.setPrice(109.0);
book2.setPublisher("机械工业出版社");
book2.setPublishYear(2013);
// ... 创建8个Book对象(省略部分代码)
```
接下来我们需要将这10个Book对象以对象形式存入文件中:
```java
List<Book> bookList = new ArrayList<>();
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("book.dat"))) {
oos.writeObject(book1);
oos.writeObject(book2);
// ... 将剩下的8个Book对象写入文件(省略部分代码)
} catch (IOException e) {
e.printStackTrace();
}
```
最后我们可以读取刚刚保存的文件,并将这些Book对象存入List集合中:
```java
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("book.dat"))) {
while (true) {
Book book = (Book) ois.readObject();
bookList.add(book);
}
} catch (EOFException e) {
// 所有Book对象已经读完
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 输出List集合中的所有Book对象
for (Book book : bookList) {
System.out.println(book);
}
```
以上就是实现的完整示例代码。如果您有任何问题,请随时问我。
阅读全文