ObjectOutputStream的writeObject()方法
Product类
import java.io.Serializable;
public class Product implements Serializable{
private int ID;
private String name;
private String categories;
private double price;
public Product() {
super();
// TODO 自动生成的构造函数存根
}
public Product(int iD, String name, String categories, double price) {
super();
ID = iD;
this.name = name;
this.categories = categories;
this.price = price;
}
public int getID() {
return ID;
}
public void setID(int iD) {
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;
}
@Override
public String toString() {
return "产品ID:" + this.ID + "\n产品名称" + this.name + "\n产品属性:" + this.categories + "\n产品价格:" + this.price;
}
}Test类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) {
Product iphone = new Product(123,"iphone","telephone",4888.0);
Product ipad = new Product(234,"ipad","computer",5088.0);
Product macbook = new Product(345,"macbook","computer",10688.0);
Product iwatch = new Product(256,"iwatch","watch",4799.0);
try {
FileOutputStream fos1 = new FileOutputStream("list.txt");
ObjectOutputStream oos1 = new ObjectOutputStream(fos1);
FileInputStream fis1 = new FileInputStream("list.txt");
ObjectInputStream ois1 = new ObjectInputStream(fis1);
oos1.writeObject(iphone);
oos1.writeObject(ipad);
oos1.writeObject(macbook);
oos1.writeObject(iwatch);
oos1.flush();
Product tem1 = (Product)ois1.readObject();
System.out.println(tem1);
Product tem2 = (Product)ois1.readObject();
System.out.println(tem2);
Product tem3 = (Product)ois1.readObject();
System.out.println(tem3);
Product tem4 = (Product)ois1.readObject();
System.out.println(tem4);
fos1.close();
oos1.close();
fis1.close();
ois1.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}ObjectOutputStream的writeObject()方法为什么不会像FileOutputStream的write()方法一样会让用户选择是覆盖还是在原内容后面续写?API里没看到相关的方法,ObjectOutputStream中有类似的方法吗?
2
收起
正在回答
2回答
同学你好,FileOutputStream的write()方法写入时默认会覆盖文件中之前的内容。
因为写入的是序列化后的对象,取出时如果有其他的值会影响对象的读取等操作。
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星