6

成像,您想检查“/folder/subfolder/subsubfolder/test/test.txt”文件是否存在,您可以执行以下操作:

DocumentFile sdCard = ...; // i have already retrieved the sd card root with the users help via SAF

String path = "<SD CARD>/folder/subfolder/subsubfolder/test/test.txt";
List<String> pathParts = Arrays.asList(path.split("/"));
DocumentFile doc = sdCard;
// go through all folders, starting at sd card, to check, if the desired file exists
for (int i = 1; i < pathParts.size(); i++)
{
    DocumentFile nextDoc = doc.findFile(pathParts.get(i));
    if (nextDoc != null)
        doc = nextDoc;
    else
    {
        doc = null;
        break;
    }
}

if (doc == null)
{
    // file does not exist
}
else
{
    // file does exist
}

这很慢,有没有更快的方法至少检查 SD 卡上是否存在文件?我不想创建每个DocumentFile只是为了检查路径是否存在......

4

2 回答 2

10
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri uri = data.getData();
    DocumentFile pickedDir = DocumentFile.fromTreeUri(MainActivity.this, uri);
    String id = DocumentsContract.getTreeDocumentId(uri); 

    /* id is :  "primary:namefolder" if user select a "namefolder" from internal storage. 
     or CABB-5641 if user select external storage,
    */

    id = id + "/folder/subfolder/subsubfolder/test/test.txt";  // your path,  you must to ensure is consistent with that chosen by the user,

    Uri childrenUri = DocumentsContract.buildDocumentUriUsingTree(uri,id);
    DocumentFile chhildfile = DocumentFile.fromSingleUri(MainActivity.this,childrenUri);

    if(chhildfile != null && chhildfile.exists()){
        Log.d("laporan file", "file ini ada");
    }
}

我不是专家,我不知道这是否适用于大多数安卓,但我已经在安卓模拟器和华硕 Zenfone 5 中尝试过,希望这会有所帮助

于 2017-03-02T12:02:50.257 回答
0

你不能用

字符串穆里 = uri.toString();

然后对每个文件夹 uri 使用共享首选项,然后在需要时调用它。

于 2022-03-04T01:27:47.947 回答