我正在填写 pdf 表单并将其保存到设备中,但第一个捕获返回以下内容:“FileNotFoundException:/storage/emulated/0/myFile.pdf:打开失败:EPERM(不允许操作)”。即使我在代码中添加了 checkPermission 函数。
这是我的代码:
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, 101);
checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, 101);
File file = new File(Environment.getExternalStorageDirectory().getPath()+ "/myFile.pdf");
try {
PdfReader reader = new PdfReader(getResources().openRawResource(R.raw.bail_1));
try {
PdfWriter writer = new PdfWriter(new FileOutputStream(file));
PdfDocument pdf = new PdfDocument(reader, writer);
pdf.close();
writer.close();
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this,"FileNotFoundException: " + e.getMessage(), Toast.LENGTH_SHORT).show;
return;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this,"FileNotFoundException: " + e.getMessage(), Toast.LENGTH_SHORT).show;
return;
}
private void checkPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
}
}
File file = new File(getFilePath("myFile.pdf"));
//and Path getting Function
private String getFilePath(String pdfName) {
ContextWrapper contextWrapper = new
ContextWrapper(getApplicationContext());
File fileDir = Environment.getExternalStorageDirectory();
File pdfFile = new File (fileDir, pdfName);
return pdfFile.getPath();
}
//Old Conventional ways do not work in some cases