[ 云计算 | AWS 实践 ] Java 应用中使用 Amazon S3 进行存储桶和对象操作完全指南
import com.amazonaws.auth.AWSCredentials;
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.Bucket;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.DeleteBucketRequest;
import com.amazonaws.services.s3.model.ListBucketsResult;
public class AmazonS3Example {
public static void main(String[] args) {
// 初始化 AWS 凭证
AWSCredentials credentials = new BasicAWSCredentials("your-access-key-id", "your-secret-access-key");
// 配置 Amazon S3 客户端
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.DEFAULT_REGION)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
// 列出所有存储桶
ListBucketsResult listBucketsResult = s3Client.listBuckets();
for (Bucket bucket : listBucketsResult.getBuckets()) {
System.out.println("* 存储桶名称: " + bucket.getName());
}
// 创建一个新的存储桶
String bucketName = "my-new-bucket";
s3Client.createBucket(new CreateBucketRequest(bucketName, Regions.DEFAULT_REGION.getName()));
System.out.println("* 创建存储桶成功: " + bucketName);
// 删除刚创建的存储桶
s3Client.deleteBucket(new DeleteBucketRequest(bucketName));
System.out.println("* 删除存储桶成功: " + bucketName);
}
}
这段代码展示了如何使用 AWS SDK for Java 进行 Amazon S3 的基本操作,包括列出所有存储桶、创建新存储桶以及删除存储桶。在实际应用中,你需要替换掉 "your-access-key-id"
和 "your-secret-access-key"
并根据需要配置正确的区域。
评论已关闭