AWS S3的Java代码实现

魏健柏
2023-12-01

官方文档: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();
    }
}

 类似资料: