android保存 读取 本地数据

android保存 读取 本地数据

一、使用步骤

1.文件的保存类

代码如下(示例):

public class Service {
    public void save(OutputStream outStream, String content) throws IOException {
        outStream.write(content.getBytes());
        outStream.close();
    }

    /*
     * 读取文件信息
     * */
    public String read(InputStream inStream) throws IOException
    {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while((len = inStream.read(buffer))!=-1)
        {
            outStream.write(buffer,0,len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return new String(data);
    }
}

2.保存到本地

MODE:操作模式
MODE:操作模式
MODE_APPEND
如果文件中已经存在内容,则在内容末尾追加
MODE_PRIVATE
文件仅能被该程序访问
MODE_WORLD_READABLE
文件允许被其它应用程序访问
MODE_WORLD_WRITEABLE
文件允许被其它应用程序访问
代码如下(示例):

	//保存数据
   ArrayList<FocusOnDataBean> data=new ArrayList<>();
   OutputStream outStream;
                try {
                        Gson g = new Gson();
                        String jsonString = g.toJson(data);
                        outStream = HomeMoreNewActivity.this.openFileOutput("cszcdata.txt", Context.MODE_PRIVATE);
                        Service service = new Service();
                        service.save(outStream, jsonString);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

3.读取本地数据

代码如下(示例):

 InputStream inStream;
        try {
            inStream = mContext.openFileInput("cszcdata.txt");
            Service service = new Service();
            String content = service.read(inStream);
            Gson gson = new Gson();
            List<FocusOnDataBean> datalist = gson.fromJson(content, new TypeToken<List<FocusOnDataBean>>() {
            }.getType());
            Log.i(TAG, "onResume: 获取保存数据"+datalist.size());
            }
        } catch ( FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值