我正在尝试使用 Java-AWS API 在 AWS S3 上上传文件。问题是我的应用程序无法上传大文件,因为堆已达到其限制。 错误:java.lang.OutOfMemoryError:Java 堆空间
我个人认为扩展堆内存不是永久的解决方案,因为我必须上传高达 100 GB 的文件。我该怎么办?
这是代码片段:
BasicAWSCredentials awsCreds = new BasicAWSCredentials(AID, Akey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.fromName("us-east-2"))
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
InputStream Is=file.getInputStream();
boolean buckflag = s3Client.doesBucketExist(ABuck);
if(buckflag != true){
s3Client.createBucket(ABuck);
}
s3Client.putObject(new PutObjectRequest(ABuck, AFkey,file.getInputStream(),new ObjectMetadata() ).withCannedAcl(CannedAccessControlList.PublicRead));
最佳答案
我强烈建议在 ObjectMetadata
上使用 setContentLength()
,因为:
..If not provided, the library will have to buffer the contents of the input stream in order to calculate it.
(..这可以预见会导致“足够大”的文件出现 OutOfMemory。)
应用于您的代码:
// ...
ObjectMetadata omd = new ObjectMetadata();
// a tiny code line, but with a "huge" information gain and memory saving!;)
omd.setContentLength(file.length());
s3Client.putObject(new PutObjectRequest(ABuck, AFkey, file.getInputStream(), omd).withCannedAcl(CannedAccessControlList.PublicRead));
// ...
关于Java 堆空间不足,无法在 AWS S3 上上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379555/