How to download image using java sdk from s3?

0

I have a program which print image contents but does not know how to download image file in the best way. Can somebody help please?

BufferedReader reader = new BufferedReader(new InputStreamReader(s3objectResponse));

		String line;            
		while ((line = reader.readLine()) != null) {            
		    System.out.println(line);
		}
asked 2 months ago24 views
1 Answer
0

Below is the code of a Java console program that downloads a file from a bucket on S3, and then saves the file on disk:

package net.codejava.aws;
 
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
 
public class S3DownloadFileExample {
     
    public static void main(String[] args) throws IOException {
        String bucket = "your-bucket-name";
        String key = "Your file.png";
         
        S3Client client = S3Client.builder().build();
         
        GetObjectRequest request = GetObjectRequest.builder()
                        .bucket(bucket)
                        .key(key)
                        .build();
         
        ResponseInputStream<GetObjectResponse> response = client.getObject(request);
                 
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(key));
         
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
         
        while ((bytesRead = response.read(buffer)) !=  -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
                             
        response.close();
        outputStream.close();
    }
}
profile picture
answered 2 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions