如何将 Pdf 转换为 base64 并编码/解码

新手上路,请多包涵

好的,我有一些 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编码前

解码后

谢谢你

原文由 DKKs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.9k
2 个回答

您可以解码 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();

原文由 Ajit Soman 发布,翻译遵循 CC BY-SA 4.0 许可协议

    if (resultCode == RESULT_OK) {

     InputStream is = null;

      try

    {

    is = getContentResolver().openInputStream(imageReturnedIntent.getData());

    }

    catch (FileNotFoundException e)
    {

     e.printStackTrace();

     }

     byte[] bytesArray = new byte[0];

    try {

      bytesArray = new byte[is.available()];

     }
    catch (IOException e) {


enter code here


     e.printStackTrace();

      }

      try
     {

      is.read(bytesArray);

    String d = Base64.encodeToString(bytesArray, android.util.Base64.DEFAULT);


                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

原文由 gowthaman C 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题