解决:java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 101584。从文件中读取base64编码字符串,再解析为图片的异常问题
一·问题描述:
1.手动实现解析base64字符串为图片功能时,总是报该异常
2.打印文件流读取的base64字符串,发现最后一位字符也被读取成功了
3.不在IDEA当中创建文本文件存放base64字符串数据时,却能够正常解析为图片
二·问题原因:
1.在IDEA当中创建文本文件,存放base64字符串数据时,IDEA会在最后默认添加换行符。肉眼很容易忽略,代码解析时就容易存在异常。
2.如果是在电脑文件系统中创建文本文件,存放base64字符串数据时,则不会在文件末尾自动添加换行符
三·解决方案:
方案一:在电脑文件系统中创建txt文件,存放base64字符串数据
解析base64字符串实例代码,如下:
@Test
public void test3() throws IOException {
FileReader fileReader = new FileReader("/Users/ideal/Downloads/Base64Data");
FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/map6.png");
try {
char[] chars = new char[100];
int length = 0;
StringBuilder result = new StringBuilder();
while ((length = fileReader.read(chars)) != -1) {
result.append(new String(chars, 0, length));
}
//打印读取的数据
System.out.println(result.toString());
Base64.Decoder decoder = Base64.getDecoder();
byte[] decode = decoder.decode(result.toString());
fileOutputStream.write(decode, 0, decode.length);
fileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
fileOutputStream.close();
fileReader.close();
}
}
方案二:在IDEA中创建txt文件,存放base64字符串数据
步骤一:在IDEA的资源目录中,创建文件存储base64字符串数据
步骤二:解析base64字符串实例代码,如下:
注意:
(1)将最终拼接的base64文本字符串,必须去除两边的空格符、换行符等等
(2)如有必要,可以把中间的换行符这些也替换为空格
@Test
public void test3() throws IOException {
FileReader fileReader = new FileReader("src/test/resources/temp");
FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/map5.png");
try {
char[] chars = new char[100];
int length = 0;
StringBuilder result = new StringBuilder();
while ((length = fileReader.read(chars)) != -1) {
result.append(new String(chars, 0, length));
}
//打印读取的数据
System.out.println(result.toString());
Base64.Decoder decoder = Base64.getDecoder();
String base64Str = result.toString();
//将最终拼接的base64文本字符串,必须去除两边的空格符、换行符等等
base64Str = base64Str.trim();
//如有必要,可以把中间的换行符这些也替换为空格
base64Str = base64Str.replaceAll("\r|\n", "");
byte[] decode = decoder.decode(base64Str);
fileOutputStream.write(decode, 0, decode.length);
fileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
fileOutputStream.close();
fileReader.close();
}
}
步骤三:验证结果,成功!