Get list of files in Cloud Storage (Java)

2019-04-05 21:55发布

Is there any possibility to list all files on my Google Cloud Storage bucket with the GAE SDK? I know that the Python SDK supports such a function, but I can't find a similar function in the Java SDK.

If not available, will this be added in the future releases of the Java SDK?

2条回答
Deceive 欺骗
2楼-- · 2019-04-05 22:43

You can also do this using the Google Java Client Library (which is replacing the Google Cloud Storage API)

GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();

ListResult result = gcsService.list(appIdentity.getDefaultGcsBucketName(), ListOptions.DEFAULT);
while (result.hasNext()){
    ListItem l = result.next();
    String name = l.getName();

    System.out.println("Name: " + name);
}

If you only want to iterate through a certain "directory", use the ListOptions builder

ListOptions.Builder b = new ListOptions.Builder();
b.setRecursive(true);
b.setPrefix("directory");
...

ListResult result = gcsService.list(appIdentity.getDefaultGcsBucketName(), b.build());
...
查看更多
女痞
3楼-- · 2019-04-05 22:52

You can use the Cloud Storage JSON API via its client library. Once you set up your credentials you can make the call like this:

Storage storage = new Storage(httpTransport, jsonFactory, credential);
ObjectsList list = storage.objects().list("bucket-name").execute();
for (Object obj : list.getItems()) {
  //...
}

You may want to use an AppIdentityCredential in this case as well, which will allow the bucket to be owned by your application, and not by a user.

查看更多
登录 后发表回答