gpt4 book ai didi

android - 判断文件夹是否存在,不存在则创建

转载 作者:行者123 更新时间:2023-11-29 14:26:55 25 4
gpt4 key购买 nike

我注意到在 SO 上对此没有决定性的答案,所以我正在寻找问题“如何检查文件夹是否存在,如果不存在则创建它,使用Google 云端硬盘 Android API?”。理想地展示了使用 ResultCallback 的异步方法和使用 .await() 的同步方法的示例。

附言我知道 this question with the same title ,但公认的答案集中在 isTrashed() 上的已知滞后错误,并且不清楚您在代码中的哪一点真正知道该文件夹存在。其他答案似乎已过时。

最佳答案

This question - 虽然专注于滞后的删除状态问题 - 确实提供了一种用于测试文件夹是否存在的模式。

使用异步回调:

Query query = new Query.Builder()
.addFilter(Filters.and(Filters.eq(
SearchableField.TITLE, "MyFolder"),
Filters.eq(SearchableField.TRASHED, false)))
.build();
Drive.DriveApi.query(getGoogleApiClient(), query)
.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
@Override
public void onResult(DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Cannot create folder in the root.");
} else {
boolean isFound = false;
for(Metadata m : result.getMetadataBuffer()) {
if (m.getTitle().equals("MyFolder")) {
showMessage("Folder exists");
isFound = true;
break;
}
}
if(!isFound) {
showMessage("Folder not found; creating it.");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("MyFolder")
.build();
Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet)
.setResultCallback(new ResultCallback<DriveFolder.DriveFolderResult>() {
@Override
public void onResult(DriveFolder.DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
} else {
showMessage("Created a folder");
}
}
});
}
}
}
});

使用同步 .await()

Query query = new Query.Builder()
.addFilter(Filters.and(Filters.eq(
SearchableField.TITLE, "MyFolder"),
Filters.eq(SearchableField.TRASHED, false)))
.build();

DriveApi.MetadataBufferResult result = Drive.DriveApi.query(getGoogleApiClient(), query)
.await();

if (!result.getStatus().isSuccess()) {
showMessage("Cannot create folder in the root.");
} else {
boolean isFound = false;
for(Metadata m : result.getMetadataBuffer()) {
if (m.getTitle().equals("MyFolder")) {
showMessage("Folder exists");
isFound = true;
break;
}
}
if(!isFound) {
showMessage("Folder not found; creating it.");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("MyFolder")
.build();

Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(googleApiClient, changeSet).await();

if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
} else {
showMessage("Created a folder");
}
}

关于android - 判断文件夹是否存在,不存在则创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com