java中檔案轉Base64字串及Base64字串轉檔案
阿新 • • 發佈:2020-12-15
檔案轉Base64字串及Base64字串轉檔案
import org.apache.commons.codec.binary.Base64; /** * @Description: 檔案轉為base64字串。filePath:檔案路徑 * @Param: [filePath] * @return: java.lang.String * @Date: 2020/12/14 */ public static String fileToBase64(String filePath) throws IOException { File file = new File(filePath); FileInputStream inputFile = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; inputFile.read(buffer); inputFile.close(); byte[] bs = Base64.encodeBase64(buffer); return new String(bs); }
/** * @Description: base64轉檔案. * @Param: [strBase64 檔案base64字串, outFile 輸入檔案路徑] * @return: boolean * @Date: 2020/12/14 */ public static boolean base64ToFile(String strBase64, File outFile) { try { // 解碼,然後將位元組轉換為檔案 // 將字串轉換為byte陣列 byte[] bytes = java.util.Base64.getDecoder().decode(strBase64); return copyByte2File(bytes, outFile); } catch (Exception ioe) { ioe.printStackTrace(); return false; } }