publicvoidmultipartDownload(StringaccessKey,StringsecretKey,Stringregion,StringbucketName,StringsourceFileName,StringdestinationFileName)throwsException{try{// Create an S3 client using the provided access key, secret key, and regionS3Clients3Client=getAWSS3Client(accessKey,secretKey,region);// List objects in the bucket with the specified prefixListObjectsV2ResponselistObjectsV2Response=s3Client.listObjectsV2(b->b.bucket(bucketName).prefix(sourceFileName));List<S3Object>objects=listObjectsV2Response.contents();Longsize=objects.get(0).size();log.info("size of the file is {}",size);// Check if the file size is 0 and throw an exception if it isif(size==0){thrownewFileNotFoundException("File is empty");}longpartSize=1024*1024*10;// Set the part size to 10 MBlongcontentLength=size;FileOutputStreamfos=newFileOutputStream(destinationFileName);// Download the file in partsfor(longstart=0;start<contentLength;start+=partSize){longend=Math.min(start+partSize-1,contentLength-1);GetObjectRequestrangeGetObjectRequest=GetObjectRequest.builder().bucket(bucketName).key(sourceFileName).range("bytes="+start+"-"+end).build();ResponseInputStream<GetObjectResponse>responseInputStream=s3Client.getObject(rangeGetObjectRequest);byte[]buffer=newbyte[1024*1024*10];intbytesRead;while((bytesRead=responseInputStream.read(buffer))!=-1){fos.write(buffer,0,bytesRead);}responseInputStream.close();}fos.close();}catch(Exceptione){log.error("Exception Occurred while downloading files for key {} ",e.getMessage());thrownewRuntimeException(e);}}
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)