1 Answer
- Newest
- Most votes
- Most comments
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();
}
}
answered 2 years ago
Relevant content
- asked 10 months ago
- asked a month ago
- asked a year ago
- AWS OFFICIALUpdated 3 months ago
- AWS OFFICIALUpdated 3 years ago
- AWS OFFICIALUpdated 3 years ago
It worked, thanks. But can you please refactor this to use new FILE I/O ?
Your welcome Ankit. You can check this article http://www.javaroots.com/2013/05/how-to-upload-and-download-images-in.html?m=1