Java Read Amazon S3 Object as String

In previous post you saw how to delete several S3 objects from Amazon S3 using Java AWS SDK. Today I’ll show how to read specific S3 object and convert it to string. For instance if we store some JSON configurations file on S3 and our Java application needs to read it.

We’ll use StreamUtils class of Spring framework for conversion of InputStream to String. Please see the code below.

 

AWSCredentials credentials = new BasicAWSCredentials("<AWS accesskey>", "<AWS secretkey>");
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(Regions.US_EAST_2)
                    .build();
...

public String getS3ObjectContentAsString(String bucketName, String key) {
        try {
            if (key.startsWith("/")) {
                key = key.substring(1);
            }
            if (key.endsWith("/")) {
                key = key.substring(0, key.length());
            }
            try (InputStream is = s3Client.getObject(bucketName, key).getObjectContent()) {
                return StreamUtils.copyToString(is, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.