我正在尝试使用尚不存在的给定文件名生成 Uri。我已请求用户允许访问此文件夹。
基本上,我有一棵树 Uri 和一个名字,比如“untitled.abc”。
如果给定目录中已经存在 untitled.abc,我想检查 untitled1.abc 是否存在,然后检查 untitled2.abc 等等。
我目前所拥有的不起作用,并且可能是错误的方法:
static Uri getUniqueDocumentUri(Context c, String name, Uri myTreeUri){
DocumentFile folder = DocumentFile.fromTreeUri(c, myTreeUri);
if(folder != null) {
DocumentFile dFile = folder.createFile(".abc", name + ".abc");
int count = 1;
if(dFile == null) return null; //dFile IS ALWAYS NULL
while (dFile.exists()) {
dFile = folder.createFile(".abc", name + count + ".abc");
}
return dFile.getUri();
}
return null;
}
我实际上并不想创建文件,但我不知道如何为尚不存在的文件创建 uri。使用普通的 File 类很容易:
static public String getUniqueFileName(Context c, String name, String mybasePath){
File folder = new File(mybasePath);
if(!folder.exists()) folder.mkdir();
File file = new File(basePath + name + ".abc");
int count = 1;
while(file.exists()){
file = new File(basePath + name + count + ".abc");
count++;
}
return file.getName();
}
但我只是不知道如何使用 DocumentFile 和 Uri 实现相同的目标。肯定有更好的方法来做到这一点,对吧?
编辑:我想我想做的是创建一个具有给定名称和文件夹的 Uri。
Edit2:我也试过这个:
static Uri getUniqueDocumentUri(Context c, String name, Uri myTreeUri){
DocumentFile folder = DocumentFile.fromTreeUri(c, Uri.parse(mytreeUri));
if(folder != null) {
String name1 = name + ".abc";
int count = 1;
while (folder.findFile(name1) != null) {
name1 = name + count + ".abc";
count++;
}
DocumentFile newdf = folder.createFile(".abc", name1);
if(newdf == null) return null;
return newdf.getUri(); //THIS RETURNS NULL
}
return null;