Java实现AmazonS3工具类

文章目录


1. 依赖

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

2. 代码

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * bucketName 存储桶(开头结尾都不带 '/', eg: ddd)
 * key        路径(开头不带 '/', eg: product/test/xxx)
 */
public class AmazonS3Util {
    private static final Logger log = LoggerFactory.getLogger(AmazonS3Util.class);

    private static final AWSCredentials credentials = new BasicAWSCredentials("s3_access_key", "s3_secret_key");
    private static final AmazonS3 s3Client = AmazonS3ClientBuilder
            .standard()
            .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withRegion(Regions.US_EAST_1)
            .build();

    /**
     * 上传
     */
    public static boolean putObject(String bucketName, String key, String content) {
        byte[] contentBytes = content.getBytes(StringUtils.UTF8);
        InputStream input = new ByteArrayInputStream(contentBytes);
        return putObject(bucketName, key, input);
    }

    public static boolean putObject(String bucketName, String key, InputStream inputStream) {
        ObjectMetadata metadata = new ObjectMetadata();
        try {
            metadata.setContentLength(inputStream.available());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        PutObjectResult result = s3Client.putObject(bucketName, key, inputStream, metadata);
        return result != null && !result.getVersionId().isEmpty();
    }

	/**
     * 查询
     */
    public static S3Object getObject(String bucketName, String key) {
        if (s3Client.doesObjectExist(bucketName, key)) {
            return s3Client.getObject(bucketName, key);
        }
        return null;
    }

    public static String getObjectAsString(String bucketName, String key) {
        if (s3Client.doesObjectExist(bucketName, key)) {
            return s3Client.getObjectAsString(bucketName, key);
        }
        return null;
    }

	/**
     * 删除
     */
    public static void deleteObject(String bucketName, String key) {
        s3Client.deleteObject(bucketName, key);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值