英文:
How do you check if a folder exists in Google Cloud Storage using Java?
问题
我在尝试确定 Google Cloud Storage 中是否存在一个“目录/文件夹”的问题。
我知道在技术上没有“目录”或“文件夹”的概念,但我需要检查特定前缀是否存在。
以下是我检测 Blob 是否存在的方法,它可以正常工作:
public boolean doesFileExist(String bucket, String prefix) {
Blob blob = storage.get(bucket, prefix);
return blob != null;
}
这个方法在使用带有扩展名的实际文件名时似乎可以正常工作。然而,对于类似于 folder/
的情况却不起作用。
有什么建议吗?
英文:
I am having an issue trying to determine if a 'directory/folder' exists in Google Cloud Storage.
I know there is technically no concept of a 'directory' or 'folder' but I need to check if a particular prefix exists.
Here is the way i'm detecting if a Blob exists which works fine:
public boolean doesFileExist(String bucket, String prefix) {
Blob blob = storage.get(bucket, prefix);
return blob != null;
}
This seems to work when using an actual filename with an extension. However, using this for something like folder/
does not work.
Any suggestions?
答案1
得分: 5
你可以使用云存储列表 API来查询具有共享前缀的所有文件。如果你找到任何文件,那就意味着它存在。你将需要使用list()方法,并传递一组BlobListOption,其中指定前缀,可能只需要一页大小为1以提高效率。
英文:
You can use the Cloud Storage List API to query for all files with a shared prefix. If you find any files at all, then that means it exists. You will want to use the list() method and pass a set of BlobListOption that specify the prefix, and perhaps just a page size of 1 for efficiency.
答案2
得分: 5
感谢 @DougStevenson 的建议!我使用以下代码使其正常工作:
public boolean doesFileExist(String bucket, String prefix) {
Page<Blob> blobs = storage.list(bucket, BlobListOption.prefix(prefix), BlobListOption.pageSize(1));
return blobs.getValues().iterator().hasNext();
}
英文:
Thanks @DougStevenson for the suggestion! I was able to get it working with this:
public boolean doesFileExist(String bucket, String prefix) {
Page<Blob> blobs = storage.list(bucket, BlobListOption.prefix(prefix), BlobListOption.pageSize(1));
return blobs.getValues().iterator().hasNext();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论