我正在尝试创建一个应用程序,它将一些PDf文件作为base64编码的字符串存储在数据库中,然后解码它们并发送它们(使用Intent打开其他PDF阅读器)。 但有些事情不能正常运作。我知道字节数组在存储之前和之后与编码的String相同,所以这不是问题所在。 我认为问题出在创建文件以打开意图的过程中,但我不确定。
创建字符串:
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查看器无法显示该文件。我试过几个观众。我怀疑生成的文件
答案 0 :(得分:0)
原来我需要保存到外部存储而不是目录。
File dir = getStorageDir();
应该是
File dir = Environment.getExternalStorageDirectory();
然后它有效。