当前位置:   article > 正文

Amazon S3 API操作示例-java版_java s3 样例

java s3 样例

     amazon (S3) 是一个公开的服务,Web 应用程序开发人员可以使用它存储数字资产,包括图片、视频、音乐和文档等。除去aws本身的服务可以将一些内容直接存储到s3桶之外 ,在很多情况下,还需要使用s3桶和外部服务进行交互,比如下面一些场景:

  • 场景一:配置使用aws服务产生的账单费用以文件的形式定期发送到s3桶,本地服务获取这些文件,生成新的账单或进行费用监控。
  • 场景二:配置使用aws服务产生的日志文件定期发送到s3桶,本地服务获取这些文件,做数据分析,预防风险。
  • 场景三:将s3桶当做无限量永久文件存储器,定期将文件上传到s3桶。

     无论哪种场景,使用控制台手动同步这些文件显然不是明智的选择,那么就需要用到Amazon提供的各种API来实现这些操作。下面是使用java对s3桶操作的一些示例,需要的小伙伴可以使用cv大法啦。
     首先引入java版的sdk。如果是本地开发,一般可以只引入aws-java-sdk一个jar包,它包含了所有aws服务的包。而通常我们只使用aws服务的一种或几种,那么我们可以单独引入使用的相关服务的包。其中kms和core是所有服务包的依赖包,为减少因版本可能带来的问题,建议也进行显式引入。这里我选择的版本是:1.11.538。

pom.xml

  1. <!-- aws -->
  2. <dependency>
  3. <groupId>com.amazonaws</groupId>
  4. <artifactId>aws-java-sdk-core</artifactId>
  5. <version>${awsjavasdk.version}</version>
  6. <scope>compile</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>com.amazonaws</groupId>
  10. <artifactId>aws-java-sdk-kms</artifactId>
  11. <version>${awsjavasdk.version}</version>
  12. <scope>compile</scope>
  13. </dependency>
  14. <dependency>
  15. <groupId>com.amazonaws</groupId>
  16. <artifactId>aws-java-sdk-s3</artifactId>
  17. <version>${awsjavasdk.version}</version>
  18. <scope>compile</scope>
  19. </dependency>

 

连接awsAPI基本信息类,替换其中的ak、sk和区域。

AwsBaseClient

  1. package com.study.awsbase;
  2. import com.amazonaws.regions.Regions;
  3. /**
  4. * 连接aws的api的基本信息
  5. *
  6. * @author guoj
  7. * @date 2019年10月8日 10:32:17
  8. */
  9. public class AwsBaseClient {
  10. /**
  11. * Access key ID
  12. */
  13. protected String awsAccessKey = "ak";
  14. /**
  15. * Secret access key
  16. */
  17. protected String awsSecretKey = "sk";
  18. /**
  19. * 区域
  20. */
  21. protected Regions regions = Regions.CN_NORTH_1;
  22. public AwsBaseClient() {
  23. }
  24. public AwsBaseClient(String awsAccessKey, String awsSecretKey, Regions regions) {
  25. this.awsAccessKey = awsAccessKey;
  26. this.awsSecretKey = awsSecretKey;
  27. this.regions = regions;
  28. }
  29. public void setBaseClient(String awsAccessKey, String awsSecretKey, Regions regions) {
  30. this.awsAccessKey = awsAccessKey;
  31. this.awsSecretKey = awsSecretKey;
  32. this.regions = regions;
  33. }
  34. public AwsBaseClient withAwsAccessKey(String awsAccessKey) {
  35. this.awsAccessKey = awsAccessKey;
  36. return this;
  37. }
  38. public AwsBaseClient withAwsSecretKey(String awsSecretKey) {
  39. this.awsSecretKey = awsSecretKey;
  40. return this;
  41. }
  42. public AwsBaseClient withRegions(Regions regions) {
  43. this.regions = regions;
  44. return this;
  45. }
  46. }

    获取连接s3桶客户端的类。这里提供了供子类获取默认s3客户端方法,供子类获取自定义s3客户端的方法,代外部类获取s3客户端的默认以自定义方法。

AwsS3Client

  1. package com.study.s3;
  2. import com.amazonaws.auth.AWSStaticCredentialsProvider;
  3. import com.amazonaws.auth.BasicAWSCredentials;
  4. import com.amazonaws.regions.Regions;
  5. import com.amazonaws.services.s3.AmazonS3;
  6. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  7. import com.study.awsbase.AwsBaseClient;
  8. /**
  9. * 连接s3
  10. *
  11. * @author guoj
  12. * @date 2019年10月8日 10:32:17
  13. */
  14. public class AwsS3Client extends AwsBaseClient {
  15. protected AmazonS3 s3;
  16. public AwsS3Client() {
  17. super();
  18. BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
  19. this.s3 = AmazonS3ClientBuilder.standard().withRegion(regions).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
  20. }
  21. public AwsS3Client(String awsAccessKey, String awsSecretKey, Regions regions) {
  22. super(awsAccessKey, awsSecretKey, regions);
  23. BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
  24. this.s3 = AmazonS3ClientBuilder.standard().withRegion(regions).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
  25. }
  26. public void setS3Client(String awsAccessKey, String awsSecretKey, Regions regions) {
  27. setBaseClient(awsAccessKey, awsSecretKey, regions);
  28. BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
  29. this.s3 = AmazonS3ClientBuilder.standard().withRegion(regions).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
  30. }
  31. public AmazonS3 getS3Client() {
  32. return s3;
  33. }
  34. public AmazonS3 getS3Client(String awsAccessKey, String awsSecretKey, Regions regions) {
  35. BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
  36. s3 = AmazonS3ClientBuilder.standard().withRegion(regions).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
  37. return s3;
  38. }
  39. }
s3桶常用操作类。

AwsS3Bucket

  1. package com.study.s3;
  2. import com.amazonaws.regions.Regions;
  3. import com.amazonaws.services.s3.model.*;
  4. import com.amazonaws.services.s3.model.analytics.AnalyticsConfiguration;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. /**
  8. * s3桶常用操作
  9. *
  10. * @author guoj
  11. * @date 2019年10月8日 11:06:46
  12. */
  13. public class AwsS3Bucket extends AwsS3Client {
  14. /**
  15. * s3桶名称
  16. * 全球唯一,如果是中国区域,则中国区域唯一
  17. */
  18. private String bucketName = "sinnet-test-bucket-001";
  19. /**
  20. * s3区域
  21. */
  22. private String region = Regions.CN_NORTH_1.getName();
  23. /**
  24. * 列出所有的s3桶
  25. */
  26. public void listBuckets() {
  27. List<Bucket> buckets = s3.listBuckets();
  28. buckets.forEach(item -> {
  29. System.out.println(item.toString());
  30. });
  31. }
  32. /**
  33. * 创建一个s3桶-默认
  34. */
  35. public void createBucketBase() {
  36. Bucket bucket = s3.createBucket(bucketName);
  37. System.out.println(bucket.toString());
  38. }
  39. /**
  40. * 创建一个s3桶-带参数
  41. */
  42. public void createBucketWithParams() {
  43. //指定名称和区域
  44. CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName, region);
  45. //是否启用对象锁-启用后,阻止删除对象
  46. createBucketRequest.setObjectLockEnabledForBucket(true);
  47. Bucket bucket = s3.createBucket(createBucketRequest);
  48. System.out.println(bucket.toString());
  49. }
  50. /**
  51. * 删除一个s3桶
  52. */
  53. public void deleteBucket() {
  54. DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest(bucketName);
  55. s3.deleteBucket(deleteBucketRequest);
  56. System.out.println("delete bucket success");
  57. }
  58. /**
  59. * s3桶配置
  60. */
  61. public void configBucket() {
  62. /**
  63. * 加速配置
  64. */
  65. BucketAccelerateConfiguration bucketAccelerateConfiguration = new BucketAccelerateConfiguration(BucketAccelerateStatus.Enabled);
  66. s3.setBucketAccelerateConfiguration(bucketName, bucketAccelerateConfiguration);
  67. /**
  68. * 权限配置
  69. */
  70. //公共访问权限
  71. SetBucketAclRequest setBucketAclRequest = new SetBucketAclRequest(bucketName, CannedAccessControlList.Private);
  72. s3.setBucketAcl(setBucketAclRequest);
  73. //访问控制列表
  74. AccessControlList accessControlList = new AccessControlList();
  75. accessControlList.setRequesterCharged(true);
  76. accessControlList.setOwner(null);
  77. SetBucketAclRequest setBucketAclRequest2 = new SetBucketAclRequest(bucketName, accessControlList);
  78. s3.setBucketAcl(setBucketAclRequest2);
  79. /**
  80. * 分析配置
  81. */
  82. AnalyticsConfiguration analyticsConfiguration = new AnalyticsConfiguration();
  83. analyticsConfiguration.setId(null);
  84. SetBucketAnalyticsConfigurationRequest setBucketAnalyticsConfigurationRequest = new SetBucketAnalyticsConfigurationRequest(bucketName, analyticsConfiguration);
  85. s3.setBucketAnalyticsConfiguration(setBucketAnalyticsConfigurationRequest);
  86. /**
  87. * 生命周期配置
  88. */
  89. BucketLifecycleConfiguration bucketLifecycleConfiguration = new BucketLifecycleConfiguration();
  90. List<BucketLifecycleConfiguration.Rule> rules = new ArrayList();
  91. //需要预先制定规则
  92. BucketLifecycleConfiguration.Rule rule = new BucketLifecycleConfiguration.Rule().withId(null);
  93. rules.add(rule);
  94. bucketLifecycleConfiguration.setRules(rules);
  95. SetBucketLifecycleConfigurationRequest setBucketLifecycleConfigurationRequest = new SetBucketLifecycleConfigurationRequest(bucketName, bucketLifecycleConfiguration);
  96. s3.setBucketLifecycleConfiguration(setBucketLifecycleConfigurationRequest);
  97. /**
  98. * 加密配置
  99. * 当对象存储在s3时默认是加密的
  100. */
  101. SetBucketEncryptionRequest setBucketEncryptionRequest = new SetBucketEncryptionRequest();
  102. setBucketEncryptionRequest.setBucketName(bucketName);
  103. ServerSideEncryptionConfiguration serverSideEncryptionConfiguration = new ServerSideEncryptionConfiguration();
  104. //同样,需要预先制定规则
  105. serverSideEncryptionConfiguration.setRules(null);
  106. setBucketEncryptionRequest.setServerSideEncryptionConfiguration(serverSideEncryptionConfiguration);
  107. s3.setBucketEncryption(setBucketEncryptionRequest);
  108. /**
  109. * 版本控制配置
  110. */
  111. BucketVersioningConfiguration bucketVersioningConfiguration = new BucketVersioningConfiguration();
  112. bucketVersioningConfiguration.setMfaDeleteEnabled(true);
  113. bucketVersioningConfiguration.setStatus(BucketVersioningConfiguration.ENABLED);
  114. SetBucketVersioningConfigurationRequest setBucketVersioningConfigurationRequest = new SetBucketVersioningConfigurationRequest(bucketName, bucketVersioningConfiguration);
  115. s3.setBucketVersioningConfiguration(setBucketVersioningConfigurationRequest);
  116. /**
  117. * 为s3指定一个策略-s3的策略是唯一的
  118. */
  119. s3.setBucketPolicy(null);
  120. /**
  121. * 日志记录配置
  122. */
  123. s3.setBucketLoggingConfiguration(null);
  124. /**
  125. * 通知配置
  126. */
  127. s3.setBucketNotificationConfiguration(null);
  128. /**
  129. * 复制配置
  130. */
  131. s3.setBucketReplicationConfiguration(null);
  132. /**
  133. * 标签配置
  134. */
  135. s3.setBucketTaggingConfiguration(null);
  136. /**
  137. * 静态网站托管配置
  138. */
  139. s3.setBucketWebsiteConfiguration(null);
  140. /**
  141. * 指标配置
  142. */
  143. s3.setBucketMetricsConfiguration(null);
  144. }
  145. }

s3桶文件操作类:

AwsS3File

  1. package com.study.s3;
  2. import com.amazonaws.services.s3.model.*;
  3. import java.io.*;
  4. import java.util.List;
  5. /**
  6. * s3桶文件的常用操作
  7. *
  8. * @author guoj
  9. * @date 2019年10月8日 14:30:36
  10. */
  11. public class AwsS3File extends AwsS3Client {
  12. /**
  13. * s3桶名称
  14. */
  15. private String bucketName = "sinnet-test-bucket-001";
  16. /**
  17. * 上传到s3桶后的文件名
  18. */
  19. private String key = "test-folder/sinnet-test-file.txt";
  20. /**
  21. * 本地文件
  22. */
  23. private String localFilePath = "e:/test/s3/";
  24. private String localFileName = "1.txt";
  25. private String localFilePathName = localFilePath + localFileName;
  26. /**
  27. * 列出一个s3桶内的文件
  28. */
  29. public void listFiles() {
  30. //可以加入文件名前缀当作搜索条件
  31. String prefix = null;
  32. ObjectListing objectListing = s3.listObjects(bucketName, prefix);
  33. List<S3ObjectSummary> s3ObjectSummaryList = objectListing.getObjectSummaries();
  34. s3ObjectSummaryList.forEach(item -> {
  35. //文件路径及名称-如果是文件夹,以"/"标识路径
  36. System.out.print(item.getKey() + ",");
  37. //文件UUID
  38. System.out.println(item.getETag());
  39. });
  40. }
  41. /**
  42. * 上传一个文件到s3桶
  43. * 注意1:如果key相同,则替换
  44. * 注意2:如果key是一个层次路径,那么s3会自动创建相应文件夹
  45. */
  46. public void uploadFile() {
  47. File file = new File(localFilePathName);
  48. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
  49. //设置权限属性等-非必需
  50. // putObjectRequest.setCannedAcl(null);
  51. //上传
  52. PutObjectResult putObjectResult = s3.putObject(putObjectRequest);
  53. System.out.println(putObjectResult.getETag());
  54. }
  55. /**
  56. * 从s3桶删除一个文件
  57. * 注意:如果删除的是最后一个文件,那么,上层文件夹也会被同时删除
  58. */
  59. public void deleteFile() {
  60. s3.deleteObject(bucketName, key);
  61. }
  62. /**
  63. * 获取一个文件
  64. *
  65. * @throws IOException
  66. */
  67. public S3Object downloadFile() throws IOException {
  68. //获取文件
  69. S3Object s3Object = s3.getObject(bucketName, key);
  70. //s3文件输入流,继承了FilterInputStream
  71. S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();
  72. //文件属性等数据
  73. ObjectMetadata objectMetadata = s3Object.getObjectMetadata();
  74. //文件的key-可以用来获取文件名
  75. System.out.println(s3Object.getKey());
  76. //桶名
  77. System.out.println(s3Object.getBucketName());
  78. System.out.println(s3Object.getRedirectLocation());
  79. System.out.println(s3Object.getTaggingCount());
  80. return s3Object;
  81. }
  82. /**
  83. * 获取一个文件,并打印出来
  84. *
  85. * @throws IOException
  86. */
  87. public void downloadFileWithPrint() throws IOException {
  88. S3Object s3Object = s3.getObject(bucketName, key);
  89. S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();
  90. //如果是txt文件,可以把内容打印出来
  91. StringBuffer stringBuffer = new StringBuffer();
  92. byte[] buffer = new byte[1024];
  93. while ((s3ObjectInputStream.read(buffer)) != -1) {
  94. stringBuffer.append(new String(buffer, "UTF-8"));
  95. }
  96. s3ObjectInputStream.close();
  97. System.out.println(stringBuffer.toString().trim());
  98. }
  99. /**
  100. * 获取一个文件,并保存到本地
  101. *
  102. * @throws IOException
  103. */
  104. public void downloadFileWithSave() throws IOException {
  105. S3Object s3Object = s3.getObject(bucketName, key);
  106. S3ObjectInputStream s3ObjectInputStream = s3Object.getObjectContent();
  107. OutputStream os = null;
  108. try {
  109. //文件名
  110. String fileName = s3Object.getKey().substring(s3Object.getKey().lastIndexOf("/"));
  111. os = new FileOutputStream(new File(localFilePath + fileName));
  112. byte[] buffer = new byte[1024];
  113. while ((s3ObjectInputStream.read(buffer)) != -1) {
  114. os.write(buffer);
  115. }
  116. os.flush();
  117. } catch (IOException e) {
  118. e.printStackTrace();
  119. } finally {
  120. if (os != null) {
  121. os.close();
  122. }
  123. if (s3ObjectInputStream != null) {
  124. s3ObjectInputStream.close();
  125. }
  126. }
  127. }
  128. /**
  129. * 复制一个文件
  130. * 比较简单,就是复制,可以选择原文件的版本
  131. */
  132. public void copyFile() {
  133. String sourceBucketName = bucketName;
  134. String sourceKey = key;
  135. String sourceVersionId = null;
  136. String destinationBucketName = bucketName;
  137. String destinationKey = key;
  138. CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceKey, sourceVersionId, destinationBucketName, destinationKey);
  139. CopyObjectResult copyObjectResult = s3.copyObject(copyObjectRequest);
  140. System.out.println(copyObjectResult.toString());
  141. }
  142. }

    另外附上两个test类:

AwsS3BucketTest
  1. package com.study.s3;
  2. import org.junit.Test;
  3. public class AwsS3BucketTest {
  4. private AwsS3Bucket awsS3Bucket = new AwsS3Bucket();
  5. @Test
  6. public void listBuckets() {
  7. awsS3Bucket.listBuckets();
  8. }
  9. @Test
  10. public void createBucketBase() {
  11. awsS3Bucket.createBucketBase();
  12. }
  13. @Test
  14. public void createBucketWithParams() {
  15. }
  16. @Test
  17. public void deleteBucket() {
  18. awsS3Bucket.deleteBucket();
  19. }
  20. @Test
  21. public void configBucket() {
  22. awsS3Bucket.configBucket();
  23. }
  24. }
AwsS3FileTest
  1. package com.study.s3;
  2. import org.junit.Test;
  3. import java.io.IOException;
  4. public class AwsS3FileTest {
  5. private AwsS3File awsS3File = new AwsS3File();
  6. @Test
  7. public void listFiles() {
  8. awsS3File.listFiles();
  9. }
  10. @Test
  11. public void uploadFile() {
  12. awsS3File.uploadFile();
  13. }
  14. @Test
  15. public void deleteFile() {
  16. }
  17. @Test
  18. public void downloadFile() {
  19. }
  20. @Test
  21. public void downloadFileWithPrint() {
  22. try {
  23. awsS3File.downloadFileWithPrint();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. @Test
  29. public void downloadFileWithSave() {
  30. try {
  31. awsS3File.downloadFileWithSave();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. @Test
  37. public void copyFile() {
  38. }
  39. }

扫描下方二维码,加入我们,获取更多关于云计算的文章

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号