Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 463
Ian Newland Avatar asked Jan 25 '23 04:01

Ian Newland


1 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.

like image 76
Doug Stevenson Avatar answered Jan 29 '23 23:01

Doug Stevenson