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";
}