问题:我从Web服务中获取了原始PDF数据的Base64编码字符串(此数据位于我的String数组中pdfData
)。我必须使用此数据在PDF查看器中显示PDF(我正在使用随附的“ ThinkFree PDF Viewer”,因为我正在使用Android应用程序,但是可以概括地说任何PDF查看器都可以)。请注意,我仅出于测试目的而访问此数组的第0个元素(以确保在编写代码以提取所有PDF之前,我至少可以提取1个PDF)。
该代码在一个类中。首先createFile
调用该方法,然后intentOpenPDF
:
import org.apache.commons.codec.binary.Base64;
File file;
FileOutputStream outputStream;
private byte[] decodedContent;
private String[] pdfData;
private String[] pdfFileName;
public void createFile() {
decodedContent = Base64.decodeBase64(pdfData[0].getBytes());
try {
File path = new File(getFilesDir(), "PDFs");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, pdfFileName[0]);
outputStream = new FileOutputStream(file);
outputStream.write(decodedContent);
outputStream.close();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
// Make absolutely certain the outputStream is closed
try {
if (outputStream != null) {
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void intentOpenPDF() {
// Make sure the file exists before accessing it:
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
错误: Error opening file. It does not exist or cannot be read.
我条件语句,如果文件存在检查(在里面内破发点集intentOpenPDF
法),它IS通过这项检查。
调用getFilesDir()
产生的路径导致一个受保护的目录(file:/// data / data /),其中仅存储使用openFileOutput(String,int)创建的文件。我不是用这种方式创建文件的。在我的情况下,解决方案是使用getExternalFilesDir(null).getAbsolutePath()
,这将为您提供路径到应用程序内部的目录(/ storage / emulated / 0 / Android / data /)。不需要权限来读取或写入此路径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句