Get list of files and folders from specific Amazon S3 directory

Every item stored in Amazon S3 is object, not file, not folder, but object. This often confuses new programmers, because they used to deal with folders and files in file system. Today I’ll show how to retrieve a list of objects from specific folder(object) using Java.

Lets say you have S3 bucket and you storing a folder with many files and other folders inside it. Now you want to get a list of all objects inside that specific folder. This often needed if you want to copy some folder in S3 from one place to another including its content.


public List<String> getObjectslistFromFolder(String bucketName, String folderKey) {
	
	ListObjectsRequest listObjectsRequest = 
                                new ListObjectsRequest()
                                      .withBucketName(bucketName)
                                      .withPrefix(folderKey + "/");

	List<String> keys = new ArrayList<>();

	ObjectListing objects = s3Client.listObjects(listObjectsRequest);
	for (;;) {
		List<S3ObjectSummary> summaries = objects.getObjectSummaries();
		if (summaries.size() < 1) {
			break;
		}
		summaries.forEach(s -> keys.add(s.getKey()));
		objects = s3Client.listNextBatchOfObjects(objects);
	}

	return keys;
}

So This method will return the complete list of all the objects inside given S3 directory.

LEAVE A REPLY