我正在尝试从 IBM 云对象存储中的存储桶中获取文件。为此,首先我尝试读取存储桶中的所有可用文件。
private static List<String> listBuckets(AmazonS3 cosClient) {
final List<Bucket> bucketList = cosClient.listBuckets();
List<String> bucketNames = new ArrayList<String>();
for (final Bucket bucket : bucketList) {
bucketNames.add(bucket.getName());
}
return bucketNames;
}
public InputStream getCOSFile(AmazonS3 cosClient, String bucketName, String objectName){
List<String> bucketNames = listBuckets(cosClient);
if (bucketNames.contains(bucketName)){
LOGGER.info(bucketName+" exists");
getBucketContentsV2(cosClient, bucketName, 2);
}
在这里,我从 if 块中得到消息 bucketName 存在。此外,存储桶确实存在于我的云帐户中。但是,getBucketContentsV2 给了我这个错误消息:“指定的存储桶不存在。(服务:Amazon S3;状态代码:404;错误代码:NoSuchBucket;请求 ID:xxxxx)
这是 getBucketContentsV2 方法,几乎与 IBM 云文档教程中的完全一样。
public static void getBucketContentsV2(AmazonS3 cosClient, String bucketName, int maxKeys) {
System.out.printf("Retrieving bucket contents (V2) from: %s\n", bucketName);
boolean moreResults = true;
String nextToken = "";
while (moreResults) {
ListObjectsV2Request request = new ListObjectsV2Request()
.withBucketName(bucketName)
.withMaxKeys(maxKeys)
.withContinuationToken(nextToken);
ListObjectsV2Result result = cosClient.listObjectsV2(request);
for(S3ObjectSummary objectSummary : result.getObjectSummaries()) {
System.out.printf("Item: %s (%s bytes)\n", objectSummary.getKey(), objectSummary.getSize());
}
if (result.isTruncated()) {
nextToken = result.getNextContinuationToken();
System.out.println("...More results in next batch!\n");
}
else {
nextToken = "";
moreResults = false;
}
}
System.out.println("...No more results!");
}
我还尝试使用文档中的 V1 代码检索存储桶中的所有文件,并得到相同的 NoSuchBucket 错误。
这是该方法的实现:
public static void listBuckets(AmazonS3 cosClient, String bucketName) {
System.out.printf("Retrieving bucket contents from: %s\n", bucketName);
ObjectListing objectListing = cosClient.listObjects(new ListObjectsRequest().withBucketName(bucketName));
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
System.out.printf("Item: %s (%s bytes)\n", objectSummary.getKey(), objectSummary.getSize());
}
System.out.println();
}