java基础之IO流与序列化综合练习题

a.txt文件中有一些数据,格式为 age=10,name=zhangsan age=2001,name=lisi age=1,name=wangwu age=66,name=zhaoliu 1、将文件中的所有信息,通过合适的IO流读取出来,封装成Person对象,使用List集合进行存储 2、将集合对象序列化到另外一个文件persons.txt中 3、从persons.txt反序列化其中的集合,并遍历集合内容*

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Demo2 {
          
   
	public static void main(String[] args) throws Exception {
          
   
		BufferedReader br = null;
		ObjectOutputStream os = null;
		ObjectInputStream is = null;
		List<Person> list = new ArrayList<>();
		try {
          
   
			String len = "";
			int x = 0;
			int y = 0;
			br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt")));
			while ((len = br.readLine()) != null) {
          
   
				String[] strings = len.split(",");
				for (int i = 0; i < strings.length; i++) {
          
   
					// indexOf("="):得到"="位置的索引值
					x = strings[i].indexOf("=");
					// substring(x+1)把"="即其之前的去掉
					len = strings[i].substring(x + 1);
					if (i == 0) {
          
   
						// Integer.parseInt()是把()里的内容转换成整数
						y = Integer.parseInt(len);
					}
				}
				Person p = new Person(y, len);
				list.add(p);
			}
		} catch (Exception e) {
          
   
			e.printStackTrace();
		} finally {
          
   
			if (br != null) {
          
   
				br.close();
			}
		}
		try {
          
   
			// 将集合对象序列化到另外一个文件persons.txt中
			os = new ObjectOutputStream(new FileOutputStream("Person.txt"));
			// 将List集合中的对象写入Person.txt文件中
			os.writeObject(list);
			// 从persons.txt反序列化其中的集合,并遍历集合内容
			is = new ObjectInputStream(new FileInputStream("Person.txt"));
			// 读取Person.txt中的内容
			List<Person> list1 = (List<Person>) is.readObject();
			for (Person p : list1) {
          
   
				System.out.println(p);
			}
		} catch (Exception e) {
          
   
			// TODO: handle exception
			e.printStackTrace();
		} finally {
          
   
			if (os != null) {
          
   
				try {
          
   
					os.close();
				} catch (Exception e2) {
          
   
					// TODO: handle exception
					e2.printStackTrace();
				} finally {
          
   
					if (is != null) {
          
   
					}
					try {
          
   
						is.close();
					} catch (Exception e3) {
          
   
						// TODO: handle exception
						e3.printStackTrace();
					}
				}
			}

		}

	}
}

class Person implements Serializable {
          
   
	private int age;
	private String name;
	
	public int getAge() {
          
   
		return age;
	}
	
	public void setAge(int age) {
          
   
		this.age = age;
	}
	
	public String getName() {
          
   
		return name;
	}
	
	public void setName(String name) {
          
   
		this.name = name;
	}
	
	public Person(int age, String name) {
          
   
		super();
		this.age = age;
		this.name = name;
	}
	
	public Person() {
          
   
		super();
	}
	
	@Override
	public String toString() {
          
   
		return "Person [age=" + age + ", name=" + name + "]";
	}
	
}
经验分享 程序员 微信小程序 职场和发展