- import java.io.*;
- /**
- * 把对象存储在硬盘叫做对象的持久化存储,也叫对象的序列化
- * 对象的序列化
- * */
- public class ObjectStreamDemo {
- /**
- * @param args
- * @throws IOException
- * @throws ClassNotFoundException
- */
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- // writeObj();
- readObj();
- }
-
- public static void readObj() throws FileNotFoundException, IOException, ClassNotFoundException{
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
- //笨方法取出4个Person对象
- Person p1 = (Person) ois.readObject();
- Person p2 = (Person) ois.readObject();
- Person p3 = (Person) ois.readObject();
- Person p4 = (Person) ois.readObject();
- System.out.println(p1);
- System.out.println(p2);
- System.out.println(p3);
- System.out.println(p4);
- ois.close();
- }
- /**
- * 将对象Person存储起来放在obj.txt中
- * */
- public static void writeObj() throws IOException{
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
-
- oos.writeObject(new Person("zhangsan",21));
- oos.writeObject(new Person("lisi",24));
- oos.writeObject(new Person("xiaoming",33));
- oos.writeObject(new Person("guange",30));
- oos.close();
- }
- }
复制代码- import java.io.Serializable;
- public class Person implements Serializable{
- private static final long serialVersionUID = 1L;
- private String name;
- private int age;
- Person(String name,int age){
- this.name = name;
- this.age = age;
- }
- public String toString(){
- return name+":"+age;
- }
- }
复制代码
添加四个Person 对象到文本中,上面为笨方法取出4个Person对象;如何循环输出4个Person对象,求思路,求解答 |