Base64與File之間的相互轉化


原文鏈接:https://blog.csdn.net/qq_35971258/article/details/80593500   (侵刪)

/**
     *
     * @param path
     * @return String
     * @description 將文件轉base64字符串
     * @date 2018年3月20日
     * @author changyl
     * File轉成編碼成BASE64
     */
 
    public static  String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) 
                try {
                    in.close()
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }
//BASE64解碼成File文件
    public static void base64ToFile(String destPath,String base64, String fileName) {
        File file = null;
        //創建文件目錄
        String filePath=destPath;
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

需要注意:標紅的base64在這里需要去掉

baseStr = baseStr.replace("data:image/jpeg;base64,", "");//base64解密部分亂碼問題(“+” 號,在urlecode編碼中會被解碼成空格)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM