请问代码是否符合题目要求?
相关代码:
package com.imooc.files;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Product implements Serializable{
//私有属性:id,name,categories,price
private int id;
private String name;
private String categories;
private double price;
//无参构造
private Product() {
}
//带参构造
public Product(int id, String name, String categories, double price) {
super();
this.id = id;
this.name = name;
this.categories = categories;
this.price = price;
}
//getter和setter构造
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;
}
//toString构造
@Override
public String toString() {
return "apple系列产品信息:\n产品ID:" + id + "\n产品名称:" + name + "\n产品属性:" + categories + "\n产品价格:" + price + "";
}
public static void main(String[] args) {
Product product1=new Product(123,"iphone","telephone",4888.0);
Product product2=new Product(234,"ipad","computer",5088.0);
Product product3=new Product(345,"macbook","computer",10688.0);
Product product4=new Product(256,"iwatch","watch",4799.0);
try {
FileOutputStream fos=new FileOutputStream("C:\\Users\\skiiiiiiii\\Desktop\\imooc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream("C:\\Users\\skiiiiiiii\\Desktop\\imooc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
//将product对象信息写入文件中
oos.writeObject(product1);
oos.writeObject(product2);
oos.writeObject(product3);
oos.writeObject(product4);
oos.flush();
//读取信息
try {
Product product=(Product)ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fos.close();
oos.close();
fis.close();
ois.close();
System.out.println(product1);
System.out.println(product2);
System.out.println(product3);
System.out.println(product4);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
17
收起
正在回答
1回答
同学你好,代码运行结果虽与效果图一致,但代码实现有一点问题。代码中最后输出的对象是在主方法中直接创建的Project对象,而不是从文件中读取出来的对象。建议通过readObject()返回是否为空判断是否读完,即在写完对象后,再加一句oos.writeObject(null);用来判断是否读取到结尾,然后循环读取时如果为null则表示读取到文件结尾。示例代码如下:
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星