如何将 S3 对象写入文件?

问题描述:

将 S3 对象(我拥有其中的密钥)写入文件的最快方法是什么?我正在使用 Java.

What's the fastest way to write an S3 object (of which I have the key) to a file? I'm using Java.

虽然 IOUtils.copy()IOUtils.copyLarge() 很棒,但我更喜欢循环输入流的老式方法,直到输入流返回 -1.为什么?我之前使用过 IOUtils.copy() 但有一个特定的用例,如果我开始从 S3 下载一个大文件,然后由于某种原因,如果该线程被中断,下载不会停止,它会一直继续,直到整个文件被下载.

While IOUtils.copy() and IOUtils.copyLarge() are great, I would prefer the old school way of looping through the inputstream until the inputstream returns -1. Why? I used IOUtils.copy() before but there was a specific use case where if I started downloading a large file from S3 and then for some reason if that thread was interrupted, the download would not stop and it would go on and on until the whole file was downloaded.

当然,这与S3无关,只是IOUtils库.

Of course, this has nothing to do with S3, just the IOUtils library.

所以,我更喜欢这个:

InputStream in = s3Object.getObjectContent();
byte[] buf = new byte[1024];
OutputStream out = new FileOutputStream(file);
while( (count = in.read(buf)) != -1)
{
   if( Thread.interrupted() )
   {
       throw new InterruptedException();
   }
   out.write(buf, 0, count);
}
out.close();
in.close();

注意:这也意味着您不需要额外的库

Note: This also means you don't need additional libraries