redblue
redblue

Reputation: 15

AWS S3 listFiles - How can i get directory path?

Is it possible to get all files name from s3 bucket? In my local spring boot project, i wrote something like, and it works.

File[] files = new File("/myfiles").listFiles();
    for (File file : files) {
        if (file.isFile()) {
            filesDir.add(file.getName());
        }
    }

On AWS i try this, but it doesnt work.

File[] files = new File("https://s3.eu-central-1.amazonaws.com/bucket_name/myfiles/").listFiles();
        for (File file : files) {
            if (file.isFile()) {
                filesDir.add(file.getName());
            }
        }

What is wrong, how can i get directory path from s3?

Upvotes: 1

Views: 5470

Answers (1)

Cristiano Bombazar
Cristiano Bombazar

Reputation: 1042

First of all, you need to connect to S3. To do this, following below suggest. Add in your pom the AWS API

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.113</version>
</dependency>

You will create an instance of AmazonS3 service. Like this:

BasicAWSCredentials credentials = new BasicAWSCredentials("ACCESS KEY", "SECRET KEY");
AmazonS3 service AmazonS3Client.builder()
             .withClientConfiguration(clientConfiguration)
             .withEndpointConfiguration(new EndpointConfiguration("YOUR_ENDPOINT", "YOUR_REGION"))
             .withCredentials(new AWSStaticCredentialsProvider(credentials))
             .build();

After connecting, you can retrieve the information about the bucket using the service you just have created.

ListObjectsV2Request req = new ListObjectsV2Request().withBucketName("bucket").withPrefix("path_your_file_or_folder");
ListObjectsV2Result result = service.listObjectsV2(req)
for (S3ObjectSummary object: result .getObjectSummaries()){
    String key = object.getKey(); //your object it's here.
}

After getting the key to your file, you can download it. I hope this helps you.

Upvotes: 2

Related Questions