用java创建图书类Book,包含五个属性(编号bookNum、书名bookName、作者author、价格price、销量saleNum),然后创建一个Book对象并将该对象存储到文件中(序列化)。(7分)
时间: 2024-03-21 10:42:18 浏览: 152
book.java
好的,以下是Java版本的实现代码:
```java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Book implements Serializable {
private String bookNum;
private String bookName;
private String author;
private double price;
private int saleNum;
public Book(String bookNum, String bookName, String author, double price, int saleNum) {
this.bookNum = bookNum;
this.bookName = bookName;
this.author = author;
this.price = price;
this.saleNum = saleNum;
}
public String getBookNum() {
return bookNum;
}
public void setBookNum(String bookNum) {
this.bookNum = bookNum;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSaleNum() {
return saleNum;
}
public void setSaleNum(int saleNum) {
this.saleNum = saleNum;
}
public static void main(String[] args) {
// 创建一个Book对象
Book book = new Book("001", "Java编程思想", "Bruce Eckel", 88.8, 200);
try {
// 将该对象存储到文件中
FileOutputStream fileOut = new FileOutputStream("book.dat");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(book);
objOut.close();
fileOut.close();
System.out.println("Book对象已序列化并存储到book.dat文件中。");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码中,我们同样定义了一个Book类,包含五个属性,并通过实现`Serializable`接口来支持对象的序列化。接着在`main`方法中,我们创建了一个Book对象,然后使用`ObjectOutputStream`类将对象序列化并存储到名为`book.dat`的文件中。
注意:为了保证代码的正确性,你需要在执行前先检查是否已经导入了`java.io`和`java.io.Serializable`包。
阅读全文