应用对象序列化和对象反序列化向文件写入对象,并将对象读取出来输入到控制台上。任务要求: 1、创建Product类,并声明它的属性:id,name,categories,price 2、实现Serializable接口; 3、定义Product类构造方法; 4、在Test类里面,创建Product类的对象:iphone,ipad,macbook,iwatch 5、实例化对象输入流和对象输出流; 6、写入Product类的四个对象; 7、从文件里读取四个product类的四个对象。
时间: 2023-12-06 20:45:28 浏览: 71
类和对象的序列化,可以序列化程xml或者byte
下面是实现该任务的代码:
Product类:
```java
import java.io.Serializable;
public class Product implements Serializable {
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 String getName() {
return name;
}
public String getCategories() {
return categories;
}
public double getPrice() {
return price;
}
}
```
Test类:
```java
import java.io.*;
public class Test {
public static void main(String[] args) {
// 创建Product类的四个对象
Product iphone = new Product(1, "iPhone", "Mobile phone", 7999.0);
Product ipad = new Product(2, "iPad", "Tablet", 4999.0);
Product macbook = new Product(3, "MacBook", "Laptop", 12999.0);
Product iwatch = new Product(4, "iWatch", "Smart watch", 2599.0);
try {
// 实例化对象输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("products.dat"));
// 写入对象
oos.writeObject(iphone);
oos.writeObject(ipad);
oos.writeObject(macbook);
oos.writeObject(iwatch);
// 关闭对象输出流
oos.close();
// 实例化对象输入流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("products.dat"));
// 从文件里读取对象并输出到控制台上
for (int i = 0; i < 4; i++) {
Product product = (Product) ois.readObject();
System.out.println("ID: " + product.getId());
System.out.println("Name: " + product.getName());
System.out.println("Categories: " + product.getCategories());
System.out.println("Price: " + product.getPrice());
System.out.println();
}
// 关闭对象输入流
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
运行Test类,输出结果如下:
```
ID: 1
Name: iPhone
Categories: Mobile phone
Price: 7999.0
ID: 2
Name: iPad
Categories: Tablet
Price: 4999.0
ID: 3
Name: MacBook
Categories: Laptop
Price: 12999.0
ID: 4
Name: iWatch
Categories: Smart watch
Price: 2599.0
```
阅读全文