gpt4 book ai didi

java apache IOUtils 破坏文件内容

转载 作者:行者123 更新时间:2023-12-02 04:27:33 24 4
gpt4 key购买 nike

我需要将 pdf 文件编码/解码为 Base64 格式。所以我从磁盘读取文件到String(因为我将来会收到String Base64格式的文件);

String pdfString = IOUtils.toString(new FileInputStream(new
File("D:\\vrpStamped.pdf")));
byte[] encoded = Base64.encodeBase64(pdfString.getBytes());

byte[] newPdfArray = Base64.decodeBase64(encoded);
FileOutputStream imageOutFile = new FileOutputStream(
"D:\\1.pdf");
imageOutFile.write(newPdfArray);
imageOutFile.close();
imageOutFile.flush();

因此,我的 D:\\1.pdf 无法在 Adob​​eReader 中打开,但如果我直接将文件读取为字节数组,请改用 IOUtils.toByteArray(..) ,一切正常,我的 D:\\1.pdf 文件成功在 Adob​​e Reader 中打开:

byte[] encoded = Base64.encodeBase64(IOUtils.toByteArray(new FileInputStream(new File("D:\\vrpStamped.pdf"))););

在我看来,IOUtils.toString(..) 更改了文件内容中的某些内容。那么如何将文件转换为字符串而不破坏内容呢?

最佳答案

如何对 pdf 进行编码...

byte[] bytes = IOUtils.toByteArray(new FileInputStream(new File("/home/fschaetz/test.pdf")));
byte[] encoded = Base64.encode(bytes);
String str = new String(encoded);

...现在用这个编码的字符串做一些事情,例如,通过 Rest 服务发送它。

现在,如果您收到编码的字符串,您可以像这样解码并保存它......

byte[] decoded = Base64.decode(str.getBytes());
FileOutputStream output = new FileOutputStream(new File("/home/fschaetz/result.pdf"));
output.write(decoded);
output.close();

适用于所有文件,不仅限于图像或 pdf。

你的例子正在做的是......

  1. 将 pdf 读入字符串(这几乎会破坏数据,因为您正在将二进制数据读入字符串)
  2. 今年 Spring 编码(这很可能不再是原始 pdf 的有效表示)
  3. 解码并将其保存到磁盘

关于java apache IOUtils 破坏文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com