首页 > 编程 > Java > 正文

Java将对象保存到文件中/从文件中读取对象的方法

2019-11-26 13:30:10
字体:
来源:转载
供稿:网友

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;  }

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

以上这篇Java将对象保存到文件中/从文件中读取对象的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表