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

huangapple go评论81阅读模式
英文:

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&lt;Blob&gt; blobs = storage.list(bucket, BlobListOption.prefix(prefix), BlobListOption.pageSize(1));
	return blobs.getValues().iterator().hasNext();
}

huangapple
  • 本文由 发表于 2020年4月8日 04:52:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61089238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定