工具方法

1.將二進制數據保存到文件中

     /**
     * 把二進制數據轉成指定後綴名的文件,例如PDF,PNG等
     *
     * @param contents 二進制數據
     * @param filePath 文件存放目錄,包括文件名及其後綴,如D:\file\bike.jpg
     */
    public static void bytesToFile(byte[] contents, String filePath) {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream output = null;
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(contents);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            // 獲取文件的父路徑
            File path = file.getParentFile();
            if (!path.exists()) {
                Log.i("waruler", "文件夾不存在,創建。path=" + path);
                boolean isCreated = path.mkdirs();
                if (!isCreated) {
                    Log.i("waruler", "創建文件夾失敗,path=" + path);
                }
            }
            fos = new FileOutputStream(file);
            output = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
            output.flush();
        } catch (Exception e) {
            Log.i("waruler", "輸出文件流時拋異常,filePath=" + filePath, e);
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (IOException e0) {
                Log.i("waruler", "文件處理失敗,filePath=" + filePath, e0);
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章