Search code examples
javaamazon-web-servicesamazon-s3aws-sdkdeprecated

AmazonS3Client(credentials) is deprecated


I'm trying to read the files available on Amazon S3, as the question explains the problem. I couldn't find an alternative call for the deprecated constructor.

Here's the code:

private String AccessKeyID = "xxxxxxxxxxxxxxxxxxxx";
private String SecretAccessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static String bucketName     = "documentcontainer";
private static String keyName     = "test";
//private static String uploadFileName    = "/PATH TO FILE WHICH WANT TO UPLOAD/abc.txt";

AWSCredentials credentials = new BasicAWSCredentials(AccessKeyID, SecretAccessKey);

void downloadfile() throws IOException
{

    // Problem lies here - AmazonS3Client is deprecated
    AmazonS3 s3client = new AmazonS3Client(credentials);
        try {
        System.out.println("Downloading an object...");
        S3Object s3object = s3client.getObject(new GetObjectRequest(
                bucketName, keyName));
        System.out.println("Content-Type: "  +
                s3object.getObjectMetadata().getContentType());
        InputStream input = s3object.getObjectContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("    " + line);
        }
        System.out.println();
    } catch (AmazonServiceException ase) {
          //do something
    } catch (AmazonClientException ace) {
        // do something
    }
 }

Any help? If more explanation is needed please mention it. I have checked on the sample code provided in .zip file of SDK, and it's the same.


Solution

  • You can either use AmazonS3ClientBuilder or AwsClientBuilder as alternatives.

    For S3, simplest would be with AmazonS3ClientBuilder.

    BasicAWSCredentials creds = new BasicAWSCredentials("access_key", "secret_key"); 
    
    AmazonS3 s3Client = AmazonS3ClientBuilder
        .standard()
        .withCredentials(new AWSStaticCredentialsProvider(creds))
        .build();