Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

使用 AWS SDK for Java 列出键

下面的示例将列出存储桶中的对象键。该示例使用分页来检索一组对象键。如果有多个键要在第一页后要返回,Amazon S3 将在响应中包含一个延续令牌。该示例在后续请求中使用延续令牌来提取下一组对象键。

有关创建和测试有效示例的说明,请参阅测试 Amazon S3 Java 代码示例

import java.io.IOException; import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ListObjectsV2Request; import com.amazonaws.services.s3.model.ListObjectsV2Result; import com.amazonaws.services.s3.model.S3ObjectSummary; public class ListKeys { public static void main(String[] args) throws IOException { String clientRegion = "*** Client region ***"; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); System.out.println("Listing objects"); // maxKeys is set to 2 to demonstrate the use of // ListObjectsV2Result.getNextContinuationToken() ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2); ListObjectsV2Result result; do { result = s3Client.listObjectsV2(req); for (S3ObjectSummary objectSummary : result.getObjectSummaries()) { System.out.printf(" - %s (size: %d)\n", objectSummary.getKey(), objectSummary.getSize()); } // If there are more than maxKeys keys in the bucket, get a continuation token // and list the next objects. String token = result.getNextContinuationToken(); System.out.println("Next Continuation Token: " + token); req.setContinuationToken(token); } while (result.isTruncated()); } catch(AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch(SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }