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

作者:jingxian 时间:2022-06-18 21:26:42 

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,读取,文件,保存
0
投稿

猜你喜欢

  • SpringBoot 如何从配置文件读取值到对象中

    2023-10-13 15:43:15
  • 详解Java中使用泛型实现快速排序算法的方法

    2022-04-28 09:47:00
  • Android使用Rotate3dAnimation实现3D旋转动画效果的实例代码

    2023-07-30 12:21:29
  • Java设计模式之备忘录模式

    2023-08-24 06:17:05
  • 一文带你了解C#中的协变与逆变

    2022-08-06 22:31:21
  • Java线程的调度与优先级详解

    2023-04-30 13:48:13
  • 浅谈SpringBoot在使用测试的时候是否需要@RunWith

    2022-12-19 04:14:14
  • Java 数据结构之删除链表中重复的结点

    2023-11-28 15:36:22
  • Android 沉浸式状态栏及悬浮效果

    2023-07-29 23:03:15
  • Java实现短信验证码的示例代码

    2023-11-09 03:22:47
  • Spring-boot的debug调试代码实例

    2023-10-17 04:49:01
  • Android 使用gradle打包Assets目录的案例

    2023-08-05 22:29:45
  • Java基础之反射详解

    2022-06-16 12:25:11
  • 关于springboot集成swagger及knife4j的增强问题

    2023-11-29 00:43:50
  • JAVA面试题 简谈你对synchronized关键字的理解

    2022-09-17 17:06:05
  • JAVA Integer类常用方法解析

    2021-09-01 06:51:08
  • Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

    2021-11-14 11:06:11
  • winform把Office转成PDF文件

    2023-03-29 01:09:32
  • iOS新浪微博、腾讯微博分享功能实例

    2023-06-16 09:15:53
  • Java 基于tcp协议实现文件上传

    2022-04-14 04:01:29
  • asp之家 软件编程 m.aspxhome.com