字節(jié)流轉(zhuǎn)換為File對象

 /**
     * 實(shí)現(xiàn)根據(jù)okHttp中的response獲取到數(shù)據(jù)流,并寫入文件中
     * @param response
     * @param content
     * @return
     */
    private File handleWithResponse(okhttp3.Response response, String content){
        //定義輸出流和輸入流
        FileOutputStream fos = null;
        InputStream is = null;
        //定義一個(gè)緩存區(qū)
        byte[] buf = new byte[1024];
        //獲取到一個(gè)file對象
        File file = getFile(content);
        int len = 0;
        try{
            //獲取到response字節(jié)流
            is = response.body().byteStream();
            //獲取到輸出對象
            fos = new FileOutputStream(file);
            //進(jìn)行讀取
            while ((len = is.read(buf)) != -1){
                //寫入到文件中
                fos.write(buf, 0 , len);
            }
            //刷新,將緩沖區(qū)數(shù)據(jù)寫入文件
            fos.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 建立一個(gè)file對象
     * @param content
     * @return
     */
    private File getFile(String content){
        //創(chuàng)建文件夾
        File dir = new File(ApiStore.DIR_PATH  );
        if (!dir.exists()) dir.mkdirs();
        //返回file對象
        return new File(ApiStore.DIR_PATH + content);
    }


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容