The code below only works for downloading text files from a bucket in S3. This does not work for an image. Is there an easier way to manage downloads/types using the AWS SDK? The example included in the documentation does not make it apparent. Thanks!
AWSCredentials myCredentials = new BasicAWSCredentials( String.valueOf(Constants.act), String.valueOf(Constants.sk)); AmazonS3Client s3Client = new AmazonS3Client(myCredentials); S3Object object = s3Client.getObject(new GetObjectRequest("bucket", "file")); BufferedReader reader = new BufferedReader(new InputStreamReader( object.getObjectContent())); File file = new File("localFilename"); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); while (true) { String line = reader.readLine(); if (line == null) break; writer.write(line + "n"); } writer.close();
Advertisement
Answer
Instead of Reader
and Writer
classes you should be using InputStream
and OutputStream
classes:
InputStream reader = new BufferedInputStream( object.getObjectContent()); File file = new File("localFilename"); OutputStream writer = new BufferedOutputStream(new FileOutputStream(file)); int read = -1; while ( ( read = reader.read() ) != -1 ) { writer.write(read); } writer.flush(); writer.close(); reader.close();