gpt4 book ai didi

Java 堆空间不足,无法在 AWS S3 上上传文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:40 25 4
gpt4 key购买 nike

我正在尝试使用 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。)

来源:PutObjectRequest javadoc

应用于您的代码:

 // ...
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com