好的,我有一些 pdf 需要通过 base64encoder 转换为 base64。
最后,我使用解码器转换回 pdf 格式,但我的内容丢失了。
我的代码:
byte[] input_file = Files.readAllBytes(Paths.get("C:\\user\\Desktop\\dir1\\dir2\\test3.pdf"));
byte[] encodedBytes = Base64.getEncoder().encode(input_file);
String pdfInBase64 = new String(encodedBytes);
String originalString = new String(Base64.getDecoder().decode(encodedBytes));
System.out.println("originalString : " + originalString);
FileOutputStream fos = new FileOutputStream("C:\\user\\Desktop\\dir1\\dir2\\newtest3.pdf");
fos.write(originalString.getBytes());
fos.flush();
fos.close();
结果:
编码:https://pastebin.com/fnMACZzH
谢谢
最佳答案
您可以解码 base64 编码的字符串并将该 byte[]
传递给 FileOutputStream
写入方法来解决此问题。
String filePath = "C:\\Users\\xyz\\Desktop\\";
String originalFileName = "96172560100_copy2.pdf";
String newFileName = "test.pdf";
byte[] input_file = Files.readAllBytes(Paths.get(filePath+originalFileName));
byte[] encodedBytes = Base64.getEncoder().encode(input_file);
String encodedString = new String(encodedBytes);
byte[] decodedBytes = Base64.getDecoder().decode(encodedString.getBytes());
FileOutputStream fos = new FileOutputStream(filePath+newFileName);
fos.write(decodedBytes);
fos.flush();
fos.close();
关于java - 如何将 Pdf 转换为 base64 并编码/解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069359/