关于读取和写入的问题!
import java.io.*;
class test{
public static void main(String[] args) {
Product pd1 = new Product(123,"iphone","telephone",4888f);
Product pd2 = new Product(234,"ipad","computer",5088f);
Product pd3 = new Product(345,"macbook","computer",10688f);
Product pd4 = new Product(256,"iwatch","watch",4799f);
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\hello.txt");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(pd1);
out.writeObject(pd2);
out.writeObject(pd3);
out.writeObject(pd4);
out.flush();
out.close();
FileInputStream fls = new FileInputStream("C:\\Users\\Administrator\\Desktop\\hello.txt");
ObjectInputStream in = new ObjectInputStream(fls);
Product p1 = (Product) in.readObject();
Product p2 = (Product) in.readObject();
Product p3 = (Product) in.readObject();
Product p4 = (Product) in.readObject();
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
System.out.println(p4);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
如上面代码,在写入的时候把多个对象写入了进去,读取的时候不应该是一下都读取出来吗?
为什么在后面创建一个读取的对象只能输出第一个写入的对象呢?而创建多个读写对象就会按照写入的对象顺序进行输出。
是写入多少个对象就应该匹配多少个读取的对象才能输出所写入的对象吗?
12
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星