1.保存对象到文件中

Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可:

 public static void writeObjectToFile(Object obj)
    {
        File file =new File("test.dat");
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            ObjectOutputStream objOut=new ObjectOutputStream(out);
            objOut.writeObject(obj);
            objOut.flush();
            objOut.close();
            System.out.println("write object success!");
        } catch (IOException e) {
            System.out.println("write object failed");
            e.printStackTrace();
        }
    }

 

参数obj一定要实现Serializable接口,否则会抛出java.io.NotSerializableException异常。另外,如果写入的对象是一个容器,例如List、Map,也要保证容器中的每个元素也都是实现 了Serializable接口。例如,如果按照如下方法声明一个Hashmap,并调用writeObjectToFile方法就会抛出异常。但是如果是Hashmap<String,String>就不会出问题,因为String类已经实现了Serializable接口。另外如果是自己创建的类,如果继承的基类没有实现Serializable,那么该类需要实现Serializable,否则也无法通过这种方法写入到文件中。

 Object obj=new Object();
        //failed,the object in map does not implement Serializable interface
        HashMap<String, Object> objMap=new HashMap<String,Object>();
        objMap.put("test", obj);
        writeObjectToFile(objMap);

 

2.从文件中读取对象

可以利用如下方法从文件中读取对象

public static Object readObjectFromFile()
    {
        Object temp=null;
        File file =new File("test.dat");
        FileInputStream in;
        try {
            in = new FileInputStream(file);
            ObjectInputStream objIn=new ObjectInputStream(in);
            temp=objIn.readObject();
            objIn.close();
            System.out.println("read object success!");
        } catch (IOException e) {
            System.out.println("read object failed");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return temp;
    }

 

读取到对象后,再根据对象的实际类型进行转换即可。