文件轉(zhuǎn)換(Base64)

文件(pdf、ofd、txt)和Base64的互相轉(zhuǎn)化

描述:Base64是一種編碼算法,3字節(jié)擴(kuò)為4字節(jié),長度增加33%
參考鏈接:https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576

1.文件轉(zhuǎn)Base64
   /**
     * 獲取文件base64
     * @param filePath:文件本地磁盤路徑
     * @return:base64串
     */
    public static String fileToBase64(String filePath){
        String base64String=null;
        InputStream in = null;
        try {
            if(StringUtils.isNotEmpty(filePath)){
                File file=new File(filePath);
                if(file.exists()&&file.isFile()){
                    in = new FileInputStream(file);
                    byte[] bytes=new byte[(int)file.length()];
                    in.read(bytes);
                    base64String=Base64.encodeBase64String(bytes);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return base64String;
        }
2.base64轉(zhuǎn)文件
    /**
     * 將base64轉(zhuǎn)為文件
     * @param base64  文件base64
     * @param filePath 文件路徑
     */
public static void base64ToFile(String base64,String filePath) throws Exception {
        OutputStream os = null;
        try {
            if(StringUtils.isEmpty(filePath)){
                throw new Exception("文件路徑不能為空");
            }
            File file=new File(filePath);
            if(!file.exists()){
                file.createNewFile();
                os=new FileOutputStream(file);
                byte[] fileBytes = Base64.decodeBase64(base64);
                os.write(fileBytes);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(null != os){
                os.close();
            }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容