Base64解码报Illegal base64 character 3异常,求解决方案
Base64解码生成PDF时出现IllegalArgumentException的解决方法
问题背景
我有一个包含Base64编码值的文本文件,尝试将其解码后保存为PDF格式,初始代码如下:
File inputfile = new File('/Users/Downloads/DownloadedPDF.txt') File outputfile = new File('/Users/Downloads/test64.pdf') byte[] data try { FileInputStream fileInputStream = new FileInputStream(inputfile) data = new byte[(int) inputfile.length()] fileInputStream.read(data) fileInputStream.close() }catch(Exception e) { e.getStackTrace() } //Decode the data byte[] decoded = java.util.Base64.getDecoder().decode(data) try { FileOutputStream fileOutputStream = new FileOutputStream(outputfile) //Write the decoded details to the output file [pdf format] fileOutputStream.write(decoded) fileOutputStream.flush() fileOutputStream.close() }catch(Exception e) { e.getStackTrace() }
执行代码时出现如下错误:
java.lang.IllegalArgumentException: Illegal base64 character 3 at java_util_Base64$Decoder$decode$0.call(Unknown Source)
尝试使用URL解码器解码,代码如下,但仍出现相同错误:
byte[] decoded = Base64.getUrlDecoder().decode(data)
错误原因
错误中的字符3是ASCII的ETX(文本结束符),说明输入的Base64数据中混入了非Base64标准字符。常见原因包括:
- 文本文件中存在多余的换行、回车、空格或注释
- 文件读取时未完整读取内容,混入了控制字符
- 原始Base64数据本身就包含非法字符
解决方法
1. 清理Base64数据中的非法字符
读取文件内容为字符串后,过滤掉所有非Base64合法字符:
- 标准Base64合法字符:
A-Z、a-z、0-9、+、/、= - URL安全Base64合法字符:
A-Z、a-z、0-9、-、_、=
2. 修正文件读取方式
原代码使用FileInputStream.read(data)可能存在读取不完整的问题,改用更可靠的Files.readString读取完整文件内容。
修正后的完整代码
import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Base64; public class Base64ToPdfConverter { public static void main(String[] args) { File inputFile = new File("/Users/Downloads/DownloadedPDF.txt"); File outputFile = new File("/Users/Downloads/test64.pdf"); try { // 读取完整文件内容为字符串 String base64RawContent = Files.readString(inputFile.toPath(), StandardCharsets.UTF_8); // 过滤非标准Base64字符(如果是URL安全Base64,替换正则为[^A-Za-z0-9-_=]) String cleanedBase64 = base64RawContent.replaceAll("[^A-Za-z0-9+/=]", ""); // 解码Base64数据 byte[] decodedPdfData = Base64.getDecoder().decode(cleanedBase64); // 写入PDF文件,使用try-with-resources自动关闭流 try (FileOutputStream fos = new FileOutputStream(outputFile)) { fos.write(decodedPdfData); } System.out.println("PDF文件已成功生成"); } catch (Exception e) { e.printStackTrace(); } } }
额外排查步骤
- 手动打开
DownloadedPDF.txt,检查是否存在前缀(如data:application/pdf;base64,)、注释或多余换行,这些都需要清理 - 用本地工具测试Base64数据合法性,比如使用命令行:
如果该命令也失败,说明原始Base64数据本身存在问题,需要重新获取正确的编码数据openssl base64 -d -in /Users/Downloads/DownloadedPDF.txt -out /Users/Downloads/test_openssl.pdf
内容的提问来源于stack exchange,提问作者Prabu
相关产品推荐
相关产品推荐

