步骤 :装箱(1)先将数据装箱实体对象. (2)多个实体对象在装箱给实体. (3)实体集合在保存到文件拆箱:(1)先将文件中的数据拆给集合 (2)集合拆给对象 (3)集合拆给实体 public class FIle_01 { public static void main (String [] args) throws IOException, IOException{ //数据存入集合 ArrayList <Apple> list = new ArrayList<Apple>(); list.add(new Apple("001",12,30)); list.add(new Apple("002",22,40)); //集合保存到文件 ObjectOutputStream ob = new ObjectOutputStream( new FileOutputStream("D://22.txt")); ob.writeObject(list); //文件写入集合 ObjectInputStream ib = new ObjectInputStream(new FileInputStream("D://22.txt")); try { List <Apple>obj = (List<Apple>) ib.readObject() ; System.out.println(obj); // 集合写入对象 for(Apple app:obj){ System.out.println(app); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
时间: 2024-12-23 17:15:31