How do you check if a folder exists in Google Cloud Storage using Java?

Viewed 6470

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?

2 Answers

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.

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();
}
Related