android – 为什么ContentResolver.openFileDescriptor抛出IllegalArgumentException?出路?

我有两个问题,为了让我的问题在这里明确一个简短的代码片段:

ContentResolver resolver = context.getContentResolver();
DocumentsContract.deleteDocument(resolver, documentUri);
resolver.openFileDescriptor(documentUri, "rw");

该文档说明最后一行“如果URI或模式下没有文件,则抛出FileNotFoundException”.

但实际上我得到了java.lang.IllegalArgumentException.

(问题1)这是一个错误还是确定?

(问题2)openFileDescriptor()显然不是测试文档是否存在的好方法.这样做的“官方”方法是什么?

编辑(添加错误日志):

W / System.err:java.lang.IllegalArgumentException:无法确定9016-4EF8:myFolder / file1.wav是否为9016-4EF8的子级:myFolder:java.io.FileNotFoundException:缺少9016-4EF8的文件:myFolder / file1 .wav at /storage/extSdCard/myFolder/file1.wav

W / System.err:在android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)

W / System.err:在android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:148)

W / System.err:在android.content.ContentProviderProxy.openAssetFile(ContentProviderNative.java:618)

W / System.err:在android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:945)

W / System.err:在android.content.ContentResolver.openFileDescriptor(ContentResolver.java:784)

W / System.err:在android.content.ContentResolver.openFileDescriptor(ContentResolver.java:739)

和:

documentUri = “内容://com.android.externalstorage.documents/tree/9016-4EF8:MyFolder文件/文件/ 9016-4EF8:MyFolder文件/ file1.wav”

最佳答案

Is this a bug or OK?

我认为这是一个bug,因为它应该在这里抛出一个FileNotFoundException.

openFileDescriptor() is obviously not a good method to test if the document exists. What is the “official” method to do that?

简单的解决方案是使用DocumentFile及其exists()方法.

If I’m able to remove the document identified by documentUri without any problem then the nature of the actual document shouldn’t be relevant for openFileDescriptor, should it?

嗯,知道应该责怪谁是有帮助的.在这种情况下,问题在于Google.

And concerning DocumentFile: I successfully avoided it and wonder if I’m now forced to include it only because of exists()?

如果您愿意,当然欢迎您克隆其exists()的实现.礼貌的一些间接,你会发现它in DocumentsContractApi19

public static boolean exists(Context context, Uri self) {
    final ContentResolver resolver = context.getContentResolver();

    Cursor c = null;
    try {
        c = resolver.query(self, new String[] {
                DocumentsContract.Document.COLUMN_DOCUMENT_ID }, null, null, null);
        return c.getCount() > 0;
    } catch (Exception e) {
        Log.w(TAG, "Failed query: " + e);
        return false;
    } finally {
        closeQuietly(c);
    }
}
点赞