我正在尝试使用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));
我强烈建议setContentLength()on ObjectMetadata,因为:
setContentLength()
ObjectMetadata
..如果未提供,则库将必须 缓冲 输入流的内容才能对其进行计算。
(..可预料的是,这将导致“足够大”的文件上的内存不足。)
来源: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)); // ...