Java Base64编码和解码
需要的 jar 包
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.12</version> </dependency>
将pdf文件编码成Base64字符串
private static String base64Encoder(String reportFile) { File pdfFile = new File(reportFile); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; try { fileInputStream = new FileInputStream(pdfFile); bufferedInputStream = new BufferedInputStream(fileInputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream); byte[] buffer = new byte[1024]; // 字节数组 int len; try { // 从输入流中读取数据到字节数组 buffer 中 -1 if there is no more data because the end of the stream has been reached len = bufferedInputStream.read(buffer); while (len != -1) { // 从字节数组 buffer 中读取 len 字节,然后写入缓存输出流中 bufferedOutputStream.write(buffer, 0, len); len = bufferedInputStream.read(buffer); // } // 刷新缓冲的输出字节写入到基础输出流 bufferedOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } // 创建一个字节数组,并将输出流中的字节存入到字节数组中 byte [] bytes = byteArrayOutputStream.toByteArray(); try { fileInputStream.close(); bufferedInputStream.close(); byteArrayOutputStream.close(); bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 将字节转换为base64编码的字符串 return Base64.encodeBase64String(bytes); }
解码还原得到pdf文件
private static void base64Decoder(String fileBase64) { BufferedInputStream bufferedInputStream = null; FileOutputStream fileOutputStream = null; BufferedOutputStream bufferedOutputStream = null; // 对base64编码的字符串进行解析,并将结果放到字节数组中 byte [] bytes = Base64.decodeBase64(fileBase64); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); bufferedInputStream = new BufferedInputStream(byteArrayInputStream); File file = new File("C:\\Users\\mail\\test解析得到.pdf"); try { fileOutputStream = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } bufferedOutputStream = new BufferedOutputStream(fileOutputStream); byte[] buffers = new byte[1024]; try { int len = bufferedInputStream.read(buffers); while(len != -1) { bufferedOutputStream.write(buffers, 0, len); len = bufferedInputStream.read(buffers); } bufferedOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedInputStream.close(); fileOutputStream.close(); bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }