如何从 Android 上的字符串正确解码 PDF?

How to properly decode PDF from String on Android?

我正在尝试创建一个应用程序,它将一些 PDF 文件作为 base64 编码的字符串存储在数据库中,然后对它们进行解码并显示它们(意图打开其他 PDF reader)。 但是有些东西不能正常工作。我知道字节数组在存储前后与编码字符串相同,所以这不是问题。 我认为问题出在创建要打开的文件的过程中,但我不确定。

正在创建字符串:

 byte[] b = Files.toByteArray(pdf);
 String encodedFile = Base64.encodeToString(b, Base64.DEFAULT);

pdf 是我从中得到的文件:

else if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
    {
        Uri uri = data.getData();
        try {
            String fileName = uri.toString();
            fileName = fileName.substring(fileName.length()-10);
            service.addPDF(order, fileName, new File(uri.getPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateFileList();
    }

从字符串获取文件:

 case PDF:
    try {
        byte[] pdfAsBytes = Base64.decode(file.getContent(), Base64.DEFAULT);
        File dir = getStorageDir();
        File pdffile = new File(dir, file.getName());
        if(!pdffile.exists())
        {
            pdffile.getParentFile().mkdirs();
            pdffile.createNewFile();
        }
        Files.write(pdfAsBytes, pdffile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(Uri.fromFile(pdffile), "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(pdfIntent);
    } catch (IOException e) {
        e.printStackTrace();
    }

    break;

此代码运行没有错误,但 PDF 查看器无法显示该文件。我试过几个观众。我怀疑生成的文件

原来我需要保存到外部存储而不是目录。

File dir = getStorageDir();

应该是

File dir = Environment.getExternalStorageDirectory();

然后就可以了。