http系列

字节流转换为File对象

2017-03-09  本文已影响958人  大海孤了岛
 /**
     * 实现根据okHttp中的response获取到数据流,并写入文件中
     * @param response
     * @param content
     * @return
     */
    private File handleWithResponse(okhttp3.Response response, String content){
        //定义输出流和输入流
        FileOutputStream fos = null;
        InputStream is = null;
        //定义一个缓存区
        byte[] buf = new byte[1024];
        //获取到一个file对象
        File file = getFile(content);
        int len = 0;
        try{
            //获取到response字节流
            is = response.body().byteStream();
            //获取到输出对象
            fos = new FileOutputStream(file);
            //进行读取
            while ((len = is.read(buf)) != -1){
                //写入到文件中
                fos.write(buf, 0 , len);
            }
            //刷新,将缓冲区数据写入文件
            fos.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 建立一个file对象
     * @param content
     * @return
     */
    private File getFile(String content){
        //创建文件夹
        File dir = new File(ApiStore.DIR_PATH  );
        if (!dir.exists()) dir.mkdirs();
        //返回file对象
        return new File(ApiStore.DIR_PATH + content);
    }


上一篇 下一篇

猜你喜欢

热点阅读