AWS S3的Java代码实现

AWS S3的Java代码实现

官方文档:https://docs.aws.amazon.com/zh_cn/sdk-for-java/v1/developer-guide/examples-s3.html

maven依赖

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.792</version>
        </dependency>

代码实现

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import lombok.Data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Data
public class AmazonS3Util {

    private String accessKey = "你的accessKey ";
    private String secretKey = "你的secretKey ";
    private String serviceEndpoint = "你的serviceEndpoint";
    private String bucketName = "你的bucketName";

    AmazonS3 s3 = null;

    /**
     * 我是通过构造器实现s3的初始化,
     * 可以根据实际的场景和需求修改初始化的方式
     */
    public AmazonS3Util() {
        ClientConfiguration config = new ClientConfiguration();
        config.setProtocol(Protocol.HTTP);
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, Regions.CN_NORTH_1.getName());
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
        s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
    }

    /**
     * 获取bucket中所有文件
     * 此处我是写了一个统一的bucket,可以根据实际需要,修改为传参等方式
     */
    public List<S3ObjectSummary> listObject() {
        ListObjectsV2Result result = s3.listObjectsV2(bucketName);
        List<S3ObjectSummary> objects = result.getObjectSummaries();
        for (S3ObjectSummary os : objects) {
            System.out.println("* " + os.getKey()+"  :"+os.toString());
        }
        return objects;
    }

    /**
     * 上传文件
     * bucket同上,可以根据实际需要提取出来
     * file_path: 本地文件的地址,不包含文件名
     * key_name: 文件名称
     */
    public PutObjectResult putObject(String file_path, String key_name) {
        try {
            PutObjectResult putObjectResult = s3.putObject(bucketName, key_name, new File(file_path));
            return putObjectResult;
        } catch (AmazonServiceException e) {
            log.error(e.getErrorMessage());
        }
        return null;
    }

    /**
     * 下载文件
     * bucket同上,可以根据实际需要提取出来
     * file_path: 要存到本地的地址,不包含文件名
     * key_name: 文件名称
     */
    public void getObject(String file_path, String key_name) {
        try {
            S3Object o = s3.getObject(bucketName, key_name);
            S3ObjectInputStream s3is = o.getObjectContent();
            FileOutputStream fos = new FileOutputStream(new File(file_path+key_name));
            byte[] read_buf = new byte[1024];
            int read_len = 0;
            while ((read_len = s3is.read(read_buf)) > 0) {
                fos.write(read_buf, 0, read_len);
            }
            s3is.close();
            fos.close();
        } catch (AmazonServiceException e) {
            log.error(e.getMessage());
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    /**
     * 复制文件
     */
    public void copyObject(String object_key, String to_object_key) {
        try {
            CopyObjectResult copyObjectResult = s3.copyObject(bucketName, object_key, bucketName, to_object_key);
        } catch (AmazonServiceException e) {
            log.error(e.getErrorMessage());
        }
    }

    /**
     * 删除文件
     * @param object_key
     */
    public void deleteObject(String object_key){
        try {
            s3.deleteObject(bucketName, object_key);
        } catch (AmazonServiceException e) {
            log.error(e.getErrorMessage());
        }
    }

    // 调用示例
    public static void main(String[] args) {
        new AmazonS3Util().listObject();
    }
}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AWS S3 Java SDK V2 中,可以通过实现 `software.amazon.awssdk.core.sync.ResponseTransformer` 接口并重写其中的 `onResponse()` 和 `exceptionOccurred()` 方法来实现 TransferListener。在 `onResponse()` 方法中,您可以获得已经传输的字节数和需要传输的总字节数,并且可以通过它们来计算传输的进度。 以下是一个示例代码片段,展示了如何实现 TransferListener: ``` public class S3TransferListener implements ResponseTransformer<GetObjectResponse, GetObjectResponse> { private final long totalBytes; private final TransferListener listener; private long transferredBytes = 0; public S3TransferListener(long totalBytes, TransferListener listener) { this.totalBytes = totalBytes; this.listener = listener; } @Override public GetObjectResponse transformResponse(GetObjectResponse response) { // Do something with the response return response; } @Override public void onResponse(GetObjectResponse response) { try (InputStream contentStream = response.responseBody()) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = contentStream.read(buffer)) != -1) { // Update the transferred bytes transferredBytes += bytesRead; // Calculate the progress percentage int progress = (int) ((double) transferredBytes / totalBytes * 100); // Notify the listener of the progress update listener.progressChanged(ProgressEvent.builder() .bytesTransferred(transferredBytes) .totalBytes(totalBytes) .percentTransfered(progress) .build()); } } catch (IOException e) { throw new RuntimeException(e); } } @Override public void exceptionOccurred(Throwable error) { // Handle the exception } } ``` 在上面的代码中,`transferredBytes` 变量跟踪已经传输的字节数,`totalBytes` 变量是需要传输的总字节数。在 `onResponse()` 方法中,我们迭代读取传输的字节,并更新 `transferredBytes` 变量,计算进度百分比,最后通过 `listener.progressChanged()` 方法通知进度变化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值