Since Java 7 (published back in July 2011), there’s a better way: Files.copy()
utility from java.util.nio.file
.
Copies all bytes from an input stream to a file.
So you need neither an external library nor rolling your own byte array loops. Two examples below, both of which use the input stream from S3Object.getObjectContent()
.
InputStream in = s3Client.getObject("bucketName", "key").getObjectContent();
1) Write to a new file at specified path:
Files.copy(in, Paths.get("/my/path/file.jpg"));
2) Write to a temp file in system's default tmp location:
File tmp = File.createTempFile("s3test", "");
Files.copy(in, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
(Without specifying the option to replace existing file, you'll get a FileAlreadyExistsException
.)
Also note that getObjectContent()
Javadocs urge you to close the input stream:
If you retrieve an S3Object, you should close this input stream as
soon as possible, because the object contents aren't buffered in
memory and stream directly from Amazon S3. Further, failure to close
this stream can cause the request pool to become blocked.
So it should be safest to wrap everything in try-catch-finally, and do in.close();
in the finally block.
The above assumes that you use the official SDK from Amazon (aws-java-sdk-s3
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…