Download file to stream instead of File

2019-07-23 01:24发布

问题:

I'm implementing an helper class to handle transfers from and to an AWS S3 storage from my web application.

In a first version of my class I was using directly a AmazonS3Client to handle upload and download, but now I discovered TransferManager and I'd like to refactor my code to use this.

The problem is that in my download method I return the stored file in form of byte[]. TransferManager instead has only methods that use File as download destination (for example download(GetObjectRequest getObjectRequest, File file)).

My previous code was like this:

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key);
S3Object s3Object = amazonS3Client.getObject(getObjectRequest);
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);

Is there a way to use TransferManager the same way or should I simply continue using an AmazonS3Client instance?

回答1:

The TransferManager uses File objects to support things like file locking when downloading pieces in parallel. It's not possible to use an OutputStream directly. If your requirements are simple, like downloading small files from S3 one at a time, stick with getObject.

Otherwise, you can create a temporary file with File.createTempFile and read the contents into a byte array when the download is done.