AWS S3 Java 开发工具包 - 下载文件帮助

以下代码仅适用于从 S3 中的存储桶下载文本文件。这不适用于映像。是否有更简单的方法来使用 AWS 开发工具包管理下载/类型?文档中包含的示例并不明显。谢谢!

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();

答案 1

虽然Mauricio的答案中编写的代码可以正常工作 - 他关于流的观点当然是正确的 - 但亚马逊提供了一种更快的方法来将文件保存在他们的SDK中。我不知道它是否在2011年没有上市,但它现在是。

AmazonS3Client s3Client = new AmazonS3Client(myCredentials);

File localFile = new File("localFilename");

ObjectMetadata object = s3Client.getObject(new GetObjectRequest("bucket", "s3FileName"), localFile);

答案 2

而不是 和 类,你应该使用和类:ReaderWriterInputStreamOutputStream

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();