利用Object 的输入输出流,从文件中读取多个对象

来源:互联网 发布:天津摩卡软件 编辑:程序博客网 时间:2024/06/09 20:41
package com.java.io;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ObjectStream {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubtry {outToFile(); //调用写方法inFromFile(); //调用读方法} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void outToFile() throws Exception{  //对象写入到文件中ObjectOutputStream obout = new ObjectOutputStream(new FileOutputStream("D:/文档/test.txt"));  //创建对象输出流,并且用文件输出流实例化对象Person p  = new Person("张志强",27,"软件测试工程师");Person p1  = new Person("王静",19,"销售经理");Person p2  = new Person("李牧",23,"数据库管理员");obout.writeObject(p); //保存对象到文件obout.writeObject(p1); //保存对象到文件obout.writeObject(p2); //保存对象到文件obout.writeObject(null);  //增加一个空对象,用于以后读取时的判断obout.flush();   //强制刷下流;obout.close();  //关闭流}public static void inFromFile() throws Exception{//从文件中读取对象ObjectInputStream obin = new ObjectInputStream(new FileInputStream("D:/文档/test.txt"));//创建对象输入流,并且用文件输入流实例化对象// Person p=null;//      p =(Person)obin.readObject(); //读取对象,//    System.out.println(p.getName()+"\t"+p.getAge()+"\t"+p.getJob());Object obj=null;while((obj =(Person)obin.readObject())!=null){  // 如果读到的对象为空则退出循环Person  per =(Person)obj; //读取对象,System.out.println(per.getName()+"\t"+per.getAge()+"\t"+per.getJob());};obin.close();}}//声明一个类,用于存储,读取class Person implements Serializable{private String name;private int age;private String job;public Person(){}public Person(String name, int age, String job) {super();this.setName(name);this.setAge(age);this.setJob(job);}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}}


	
				
		
原创粉丝点击