如何使用 Java 检查 Google Cloud Storage 中是否存在文件夹?

Ian*_*and 4 java google-cloud-storage google-cloud-platform

我在尝试确定 Google Cloud Storage 中是否存在“目录/文件夹”时遇到问题。

我知道技术上没有“目录”或“文件夹”的概念,但我需要检查是否存在特定的前缀。

这是我检测 Blob 是否存在且工作正常的方法:

public boolean doesFileExist(String bucket, String prefix) {
    Blob blob = storage.get(bucket, prefix);
    return blob != null;
}
Run Code Online (Sandbox Code Playgroud)

当使用带有扩展名的实际文件名时,这似乎有效。但是,将它用于类似的操作folder/是行不通的。

有什么建议?

Ian*_*and 6

感谢@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();
}
Run Code Online (Sandbox Code Playgroud)


Dou*_*son 5

您可以使用Cloud Storage List API查询具有共享前缀的所有文件。如果您找到任何文件,则表示它存在。您将需要使用list()方法并传递一组指定前缀的BlobListOption,为了提高效率,可能只需要将页面大小设置为 1。