2016-11-25 78 views
0

我有以下文件夾結構的S3桶:AWS S3 - 只列出根級對象

<bucket-name> 
    folder1/ 
     .... 
    folder2/ 
     .... 
    foldern/ 
     .... 

每個文件夾中有文件,我只希望最高級別文件夾上市folder1, folder2 etc.

我發現我建議使用"/"作爲分隔符和一個空的前綴,而這正是我試圖用Java做了很多的解決方案如下片段:

ListObjectsRequest listObjects = new ListObjectsRequest() 
      .withDelimiter("/") 
      .withPrefix("") 
      .withBucketName(s3BucketName); 
    ObjectListing objects = s3.listObjects(listObjects); 
    for (S3ObjectSummary summ : objects.getObjectSummaries()) { 
     System.out.println(summ.getKey()); 
    } 

for循環仍然不打印任何鍵。有什麼我做錯了,或者這是不是這樣做?

回答

0

這是一個c#版本。應該很容易端口:

public List<string> GetBucketRootItems(string bucketName, string regionName) 
    { 
     List<string> result = new List<string>(); 
     try 
     { 
      using (var client = new AmazonS3Client(RegionEndpoint.GetBySystemName(regionName))) 
      { 
       ListObjectsV2Request request = new ListObjectsV2Request 
       { 
        BucketName = bucketName, 
        MaxKeys = 10000, 
        Delimiter = "/", 
        Prefix = "" 
       }; 

       ListObjectsV2Response response; 
       do 
       { 
        response = client.ListObjectsV2(request); 
        result.AddRange(response.CommonPrefixes); 
        request.ContinuationToken = response.NextContinuationToken; 
       } 
       while (response.IsTruncated == true); 
      } 
     } 
     catch (AmazonS3Exception amazonS3Exception) 
     { 
      if (amazonS3Exception.ErrorCode != null && (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") 
       || amazonS3Exception.ErrorCode.Equals("InvalidSecurity"))) 
      { 
       log.Error($"Check the provided AWS Credentials."); 
      } 
      else 
      { 
       log.Error($"Error occurred. Message:'{amazonS3Exception.Message}' when listing objects", amazonS3Exception); 
      } 
     } 
     return result; 
    } 

這似乎工作。我剛下10000項

+0

我知道這是一個老的文章,但我有同樣的問題,並想出了答案。 – ginalster

0

我設法與列出最高級別文件夾下(在Java中):

ListObjectsRequest listObjectsRequest = new ListObjectsRequest() 
             .withBucketName(bucketName) 
             .withDelimiter("/"); 
ObjectListing objectListing = client.listObjects(listObjectsRequest); 
List<String> commonPrefixes = objectListing.getCommonPrefixes(); 

你只需要設置分隔符從常用前綴讀取。我目前使用

的SDK版本爲1.10.14

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