Android Q openFd: java.io.FileNotFoundException: open failed



当我尝试打开一个文件时,我有openFd:java.io.FileNotFoundException:打开失败:EACCES(权限被拒绝(。我这样做:

这是我的提供者

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files"
path="Android/data/xxx/files/Download" />
</paths>

我把它放在清单中

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="xxx.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths2" />
</provider>

我这样做:

public static void parseBase64ToPDFAndNoOpen(String base64, String cardId ,Context context) throws IOException {
FileOutputStream os;
String path;
Uri photoURI = null;
try {
photoURI = FileProvider.getUriForFile(context.getApplicationContext(),
BuildConfig.APPLICATION_ID + ".provider", createImageFile(context,cardId));
} catch (IOException e) {
e.printStackTrace();
}
File dwldsPath = new File(photoURI.toString());
//            File dwldsPath = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + cardId + ".pdf");
if (!dwldsPath.exists()) {
dwldsPath.createNewFile();
byte[] pdfAsBytes = Base64.decode(base64, 0);
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
}
}
private static File createImageFile(Context context, String name) {
return new File(getDefaultTempFilesPath(context), name + ".pdf");

}

private static String getDefaultTempFilesPath(Context context) {
if (context != null) {
File f = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (f != null)
return f.getPath();
else {
f = context.getFilesDir();
if (f != null)
return f.getPath();
}
}
return null;
}

我在控制台的登录中看到:openFd:java.io.FileNotFoundException:打开失败:EACCES(权限被拒绝( pdf加载器:无法加载文件(无法打开(显示数据 [PDF : b2921c40-5fe2-457b-8700-e0fe26bde42c.pdf] +文件可打开,URI:

使用FileDescriptor进行FileOutputStream,这解决了我的问题:

public static void parseBase64ToPDFAndNoOpen(String base64, String cardId, Context context) throws IOException {
FileOutputStream os;
String path;
Uri photoURI = null;
try {
photoURI = FileProvider.getUriForFile(context.getApplicationContext(),
BuildConfig.APPLICATION_ID + ".provider", createImageFile(context, cardId));
} catch (IOException e) {
e.printStackTrace();
}
ParcelFileDescriptor descriptor = context.getContentResolver().openFileDescriptor(photoURI, "rw");
byte[] pdfAsBytes = Base64.decode(base64, 0);
os = new FileOutputStream(descriptor.getFileDescriptor());
os.write(pdfAsBytes);
os.flush();
os.close();
}

最新更新