(简答题) 编程练习: 应用对象序列化和对象反序列化向文件写入对象,并将对象读取出来输入到控制台上。 效果图: 任务要求: 1、创建Product类,并声明它的属性:id,name,categories,price 2、实现Serializable接口; 3、定义Product类构造方法; 4、在Test类里面,创建Product类的对象:iphone,ipad,macbook,iwatch 5、实例化对象输入流和对象输出流; 6、写入Product类的四个对象; 7、从文件里读取四
时间: 2023-12-06 13:45:18 浏览: 138
个对象并输出到控制台上。
代码如下:
Product类:
```java
import java.io.Serializable;
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String categories;
private double price;
public Product(int id, String name, String categories, double price) {
this.id = id;
this.name = name;
this.categories = categories;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
```
Test类:
```java
import java.io.*;
public class Test {
public static void main(String[] args) {
Product iphone = new Product(1, "iPhone", "Mobile Phone", 6999.0);
Product ipad = new Product(2, "iPad", "Tablet", 3999.0);
Product macbook = new Product(3, "MacBook", "Laptop", 12999.0);
Product iwatch = new Product(4, "iWatch", "Smart Watch", 1999.0);
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
// 写入对象
oos = new ObjectOutputStream(new FileOutputStream("product.dat"));
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
// 读取对象并输出到控制台
ois = new ObjectInputStream(new FileInputStream("product.dat"));
Product p = null;
while ((p = (Product) ois.readObject()) != null) {
System.out.println(p.getId() + "\t" + p.getName() + "\t" + p.getCategories() + "\t" + p.getPrice());
}
} catch (EOFException e) {
// 读到文件末尾
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
运行结果:
```
1 iPhone Mobile Phone 6999.0
2 iPad Tablet 3999.0
3 MacBook Laptop 12999.0
4 iWatch Smart Watch 1999.0
```
阅读全文