AWS S3 Java SDK - Download file help

Viewed 79018

The code below only works for downloading text files from a bucket in S3. This does not work for an image. Is there an easier way to manage downloads/types using the AWS SDK? The example included in the documentation does not make it apparent. Thanks!

AWSCredentials myCredentials = new BasicAWSCredentials(
       String.valueOf(Constants.act), String.valueOf(Constants.sk)); 
AmazonS3Client s3Client = new AmazonS3Client(myCredentials);        
S3Object object = s3Client.getObject(new GetObjectRequest("bucket", "file"));

BufferedReader reader = new BufferedReader(new InputStreamReader(
       object.getObjectContent()));
File file = new File("localFilename");      
Writer writer = new OutputStreamWriter(new FileOutputStream(file));

while (true) {          
     String line = reader.readLine();           
     if (line == null)
          break;            

     writer.write(line + "\n");
}

writer.close();
6 Answers

There is even much simpler way to get this. I used below snippet. Got reference from http://docs.ceph.com/docs/mimic/radosgw/s3/java/

AmazonS3 s3client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build();

s3client.getObject(
                new GetObjectRequest("nomad-prop-pics", "Documents/1.pdf"),
                new File("D:\\Eka-Contract-Physicals-Dev\\Contracts-Physicals\\utility-service\\downlods\\1.pdf")
    );

Use java.nio.file.Files to copy S3Object to local file.

public File getFile(String fileName) throws Exception {
    if (StringUtils.isEmpty(fileName)) {
        throw new Exception("file name can not be empty");
    }
    S3Object s3Object = amazonS3.getObject("bucketname", fileName);
    if (s3Object == null) {
        throw new Exception("Object not found");
    }
    File file = new File("you file path");
    Files.copy(s3Object.getObjectContent(), file.toPath());
    return file;
}

Dependencies AWS S3 bucket

implementation "commons-logging:commons-logging-api:1.1"
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
implementation 'com.amazonaws:aws-android-sdk-core:2.6.0'
implementation 'com.amazonaws:aws-android-sdk-cognito:2.2.0'
implementation 'com.amazonaws:aws-android-sdk-s3:2.6.0'

Download object from S3 bucket and store in local storage.

try {
                //Creating credentials
                AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);

                //Creating S3
                AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);

                //Creating file path
                File dir = new File(this.getExternalFilesDir("AWS"),"FolderName");
                if(!dir.exists()){
                    dir.mkdir();
                }

                //Object Key
                String bucketName = "*** Bucket Name ***";
                String objKey = "*** Object Key ***";
                
                //Get File Name from Object key
                String  name = objKey.substring(objKey.lastIndexOf('/') + 1);

                //Storing file S3 object in file path
                InputStream in = s3Client.getObject(new GetObjectRequest(bucketName, objKey)).getObjectContent();
                Files.copy(in,Paths.get(dir.getAbsolutePath()+"/"+name));
                in.close();

            } catch (Exception e) {
                Log.e("TAG", "onCreate: " + e);
            }

Get List of Object from S3 Bucket

public void getListOfObject()
    {
        ListObjectsV2Result result ;
        AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
        AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);
        result = s3Client.listObjectsV2(AWS_BUCKET);
        for( S3ObjectSummary s3ObjectSummary : result.getObjectSummaries())
        {
            Log.e("TAG", "onCreate: "+s3ObjectSummary.getKey() );
        }
    }

Check if any object exists in bucket or not

public String isObjectAvailable(String object_key)
    {

        try {
            AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
            AmazonS3 s3 = new AmazonS3Client(awsCredentials);
            String bucketName = AWS_BUCKET;
            S3Object object = s3.getObject(bucketName, object_key);
            Log.e("TAG", "isObjectAvailable: "+object.getKey()+","+object.getBucketName() );
        } catch (AmazonServiceException e) {
            String errorCode = e.getErrorCode();
            if (!errorCode.equals("NoSuchKey")) {
               // throw e;
                Log.e("TAG", "isObjectAvailable: "+e );
            }

            return "no such key";
        }
        return "null";
    }
Related