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;
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);
}
}