base64字符串转PDF文件

该代码片段展示了如何使用Java的BASE64Decoder将Base64编码的字符串解码并转换为PDF文件,涉及字节数组、输入输出流的处理,最终将内容写入指定路径的PDF文件。
    /**
     * base64转PDF
     * @param base64sString
     * @param pathname 生成PDF文件的 路径+文件名(如:C:/test.pdf)
     */
    static void base64StringToPDF(String base64sString, String pathname) {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            // 将base64编码的字符串解码成字节数组
            byte[] bytes = decoder.decodeBuffer(base64sString);
            // 创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            // 创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            // 指定输出的文件
            File file = new File(pathname);
            // 创建到指定文件的输出流
            fout = new FileOutputStream(file);
            // 为文件输出流对接缓冲输出流对象
            bout = new BufferedOutputStream(fout);
            byte[] buffers = new byte[1024];
            int len = bin.read(buffers);
            while (len != -1) {
                bout.write(buffers, 0, len);
                len = bin.read(buffers);
            }
            bout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bin.close();
                fout.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

### 将Base64编码的字符串换为文件 为了实现将Base64编码的字符串换成实际文件,通常有两种主要方式:一种是在内存中处理并直接写入磁盘;另一种是通过流的形式逐步读取和写出数据。这里提供一个基于Java环境下的解决方案。 #### 方法一:直接解码至字节数组再创建文件 这种方法适用于较小尺寸的数据,比如头像大小级别的图片[^2]。代码片段展示了如何把给定的Base64字符串解析成为二进制数组,并最终保存为目标文件: ```java import java.io.File; import java.io.FileOutputStream; import java.util.Base64; public class Base64ToFile { public static void main(String args[]) throws Exception{ String base64ImageString = "your_base_64_encoded_string_here"; // 替换成真实的base64字符串 File file = new File("output_image.png"); try (FileOutputStream fos = new FileOutputStream(file)) { byte[] imageBytes = Base64.getDecoder().decode(base64ImageString); fos.write(imageBytes); } } } ``` 此段程序首先定义了一个目标文件`file`,接着利用`Base64.Decoder`类中的静态方法`.getDecoder()`获得解码器实例,之后调用其`.decode()`函数完成从Base64字符序列向原始字节形式的变过程。最后借助于`FileOutputStream`对象将这些字节依次追加到指定位置处的新建或已存在的文件实体内。 #### 方法二:采用输入/输出流分批处理大数据量情况 当面对较大的Base64字符串时——例如大型文档扫描件或其他多媒体资源,则建议采取更高效的方法来避免一次性加载过多内容进入RAM而导致性能下降甚至溢出错误的发生。此时可考虑引入缓冲机制配合InputStream与OutputStream共同作用以达到目的: ```java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.util.Base64; public class LargeBase64ToStream { private static final int BUFFER_SIZE = 8 * 1024; public static void convertLargeBase64ToFile(String base64Data, String outputPath) throws Exception { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(Base64.getDecoder().decode(base64Data)); bis = new BufferedInputStream(bais); File outputFile = new File(outputPath); bos = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1){ bos.write(buffer, 0, bytesRead); } } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } public static void main(String[] args)throws Exception{ String largeBase64EncodedString="very_large_base64_encoded_data"; convertLargeBase64ToFile(largeBase64EncodedString,"large_output_file.pdf"); } } ``` 上述例子中设置了固定的缓存区大小(BUFFER_SIZE),并通过循环迭代的方式逐块读取消息体直至结束标志位(-1),期间不断更新目的地文件的内容直到整个流程完毕为止。这种方式不仅能够有效降低单次操作所需消耗的时间成本,同时也大大减少了对物理内存的压力。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值