欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java使用ObjectInputStream从文件中读取对象,,下面例子演示如何从文件中

来源: javaer 分享于  点击 46879 次 点评:288

java使用ObjectInputStream从文件中读取对象,,下面例子演示如何从文件中


下面例子演示如何从文件中读取已经序列化的对象。

我们简单的创建了一个ObjectInputStream对象,然后循环读取其中的对象,知道文件结束抛出EOFException

import java.io.EOFException;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.ObjectInputStream;/** * * @author javadb.com */public class Main {    /**     *ObjectInputStream 使用示例     */    public void readPersons(String filename) {        ObjectInputStream inputStream = null;        try {            //构造ObjectInputStream对象            inputStream = new ObjectInputStream(new FileInputStream(filename));            Object obj = null;            while ((obj = inputStream.readObject()) != null) {                if (obj instanceof Person) {                    System.out.println(((Person)obj).toString());                }            }        } catch (EOFException ex) { //在读取到文件结束时触发此异常            System.out.println("End of file reached.");        } catch (ClassNotFoundException ex) {            ex.printStackTrace();        } catch (FileNotFoundException ex) {            ex.printStackTrace();        } catch (IOException ex) {            ex.printStackTrace();        } finally {            //Close the ObjectInputStream            try {                if (inputStream != null) {                    inputStream.close();                }            } catch (IOException ex) {                ex.printStackTrace();            }        }    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().readPersons("myFile.txt");    }}
相关栏目:

用户点评