本文共 2682 字,大约阅读时间需要 8 分钟。
在项目中添加 sun.misc.BASE64Encoder
和 sun.misc.BASE64Decoder
包。
.jre
System Library中,权限可能不允许访问这些类。为了解决此问题,您需要: sun.misc
包,右键选择“可访问性”并输入*
, 依次输入允许的版本号。如果您遇到无法访问 sun.misc.BASE64Encoder
或其他问题,建议考虑以下解决方案:
javax.xml.bind.DatatypeConverter
(适用于 Java 8 及以上)或 Apache 的 Base64 库。以下是对代码的解释及优化建议:
private static String fromPdfToBinary(String filePath) { try { FileInputStream fis = new FileInputStream(new File(filePath)); BufferedInputStream bis = new BufferedInputStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); byte[] bytes = new byte[1024]; int len = bis.read(bytes); while (len != -1) { bos.write(bytes, 0, len); len = bis.read(bytes); } bos.flush(); byte[] bys = baos.toByteArray(); return encoder.encodeBuffer(bys).trim(); } catch (FileNotFoundException | IOException e) { e.printStackTrace(); }}
优化建议:
DataOutputStream
来提高读取效率。try-with-resources
来自动处理输入流和输出流资源。private static void fromBinaryToPdf(String pdfBase64Str, String filePath) { try { byte[] bytes = decoder.decodeBuffer(pdfBase64Str); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedInputStream bis = new BufferedInputStream(bais); File file = new File(filePath); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffers = new byte[1024]; int len = bis.read(buffers); while (len != -1) { bos.write(buffers, 0, len); len = bis.read(buffers); } bos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); fos.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } }}
优化建议:
finally
块中确保所有流都被正确关闭,避免资源泄漏。ByteArrayInputStream
和ByteArrayOutputStream
来减少中间对象的数量。filePath
和pdfBase64Str
用法正确,路径完整。如果不想手动处理 Base64 编码,可以使用在线工具或开源库:
Base64
编码功能。建议参考相关文档,确保您的工具支持需要的编码和解码方式。
如果您有更多技术问题,欢迎随时咨询!
转载地址:http://yidgz.baihongyu.com/