Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a "folder" exists in S3

Tags:

java

amazon-s3

I'm having a bit of trouble with this code:

public boolean isExists(String key) {
    try {
        this.s3Client.getObjectMetadata(this.bucketName, key);
        return true;
    } catch (AmazonServiceException var3) {
        return false;
    }
}

It always returns false, even if the "folder" in S3 exists (either empty or non-empty), what could be wrong?

The s3Client in the code above is just a simple AmazonS3 client:

AmazonS3 s3client = AmazonS3ClientBuilder
    .standard()
    .withCredentials(new AWSStaticCredentialsProvider(credentials))
    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(objectStoreEndpoint, objectStoreRegion))
    .build();

What's the proper way to check if folder exists in S3?

like image 507
Fireburn Avatar asked Oct 19 '25 03:10

Fireburn


1 Answers

The solution to this is to do:

public boolean isExists(String key) {
    ListObjectsV2Result result = this.s3Client.listObjectsV2(this.bucketName, key);
    return result.getKeyCount() > 0;
}

An empty "folder" (virtually speaking) would return key count of 1.

like image 103
quarks Avatar answered Oct 20 '25 16:10

quarks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!