转pdf核心代码
public static void base64StringToPdf(String base64Content,String filePath,Base64Listen base64Listen){
if (TextUtils.isEmpty(base64Content)){
return;
}
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
// 将base64编码的字符串解码成字节数组
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); //base64编码内容转换为字节数组:DEFAULT
//创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
//创建从底层输入流中读取数据的缓冲输入流对象
bis = new BufferedInputStream(byteInputStream);
// 指定输出的文件
File file = new File(filePath);
File path = file.getParentFile();
if(!path.exists()){
path.mkdirs();
}
// 创建到指定文件的输出流
fos = new FileOutputStream(file);
// 为文件输出流对接缓冲输出流对象
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int length = bis.read(buffer);
while(length != -1){
bos.write(buffer, 0, length);
length = bis.read(buffer);
}
// 刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
bos.flush();
base64Listen.onSuccess();
} catch (Exception e) {
e.printStackTrace();
base64Listen.onFail(e.toString()+"");
}finally{
try {
if (bis != null){
bis.close();
}
if (fos != null){
fos.close();
}
if (bos != null){
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
base64Listen.onFail(e.toString()+"");
}
}
}
成功失败接口
public interface Base64Listen{
void onSuccess();
void onFail(String hint);
}
base64一直转失败的原因
当你发现你代码没问题,但就是不成功,很可能问题其它原因导致
- base64数据本身就有问题,查看方式就是看看接口返回的数据是否有“+”号;