android将对象写入文件和从文件中读取对象数据

本博客详细介绍了如何使用Gson库解析JSON数据,筛选出理财师列表,并将其持久化存储到本地文件中。通过FileOutputStream和ObjectOutputStream实现数据的写入,确保数据在应用重启时仍能获取到最新的理财师列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try{
   JSONObject jsonObject=new JSONObject(msg);
   String status=jsonObject.getString("status");
   if(status.equals("1")){
      Gson gson=new Gson();
      teacherResponseList=gson.fromJson(jsonObject.getJSONArray("result").toString(),new TypeToken<List<TeacherResponse>>(){}.getType());
      Log.d("queryteacherandgroup",msg);
      Log.d("query", "查询理财师列表ONACTIVITYCreatedOEHttpCallBack");

      File teacherFile = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "teacher.dat");
      if (!teacherFile.getParentFile().exists()) {
         teacherFile.getParentFile().mkdirs();
      }
      if (!teacherFile.exists()) {
         teacherFile.createNewFile();
      }
      fileOutputStream = new FileOutputStream(teacherFile.toString());
      objectOutputStream = new ObjectOutputStream(fileOutputStream);
      objectOutputStream.writeObject(teacherResponseList);

   }
}catch (Exception e){
   e.getStackTrace();
}finally {
   if (fileOutputStream != null) {
      try {
         fileOutputStream.close();

      } catch (Exception e) {
         e.getStackTrace();
      }
      if (objectOutputStream != null) {
         try {
            objectOutputStream.close();

         } catch (Exception e) {
            e.getStackTrace();
         }
      }
   }
   //mGroupAdapter.notifyDataSetChanged();


}

 FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;
    try{
        File teacherFile = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "teacher.dat");
        if (!teacherFile.getParentFile().exists()) {
            teacherFile.getParentFile().mkdirs();
        }
        if (!teacherFile.exists()) {
            teacherFile.createNewFile();
        }
        fileInputStream = new FileInputStream(teacherFile.toString());
        objectInputStream = new ObjectInputStream(fileInputStream);
        teacherResponseList=(List<TeacherResponse> )objectInputStream.readObject();
    }catch (Exception e){
        e.getStackTrace();
    }finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();

            } catch (Exception e) {
                e.getStackTrace();
            }
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();

                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值