读取数据时默认是不能以null作为文件读取结束的标志的,可以用什么标志?
运行时异常
package com.yito.product; import java.io.Serializable; public class Product implements Serializable { private String id;//商品编号 private String name;//商品名称 private String categories;//商品属性 private double price;//商品价格 //构造方法 public Product(){ } public Product(String id, String name, String categories, double price){ this.setId(id); this.setName(name); this.setCategories(categories); this.setPrice(price); } //set/get public String getId() { return id; } public void setId(String 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 "产品ID:"+this.getId()+'\n' +"产品名称:"+this.getName()+'\n' +"产品属性:"+this.getCategories()+'\n' +"产品价格:"+this.getPrice(); } }
package com.yito.product; import java.io.*; public class Test { public static void main(String[] args) { //实现化商品对象并赋值 Product iphone = new Product("123", "iphone","telephone",4888); Product ipad = new Product("234","ipad","computer",5088); Product macbook = new Product("345","macbook","computer",10688); Product iwatch = new Product("256","iwatch","watch",4799); try { //创建对象输入输出流 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Product.txt")); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Product.txt")); //将对象信息写入文件 oos.writeObject(iphone); oos.writeObject(ipad); oos.writeObject(macbook); oos.writeObject(iwatch); oos.flush(); //读取对象信息 System.out.println("apple系列产品信息:"); Product product =null; while (( product = (Product) ois.readObject())!=null) { System.out.println(product); System.out.println(); } oos.close(); ois.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
22
收起
正在回答 回答被采纳积分+1
1回答
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星