LoginSignup
3
6

More than 5 years have passed since last update.

JavaでGoogle Cloud Storageのオブジェクトリストを取得する

Posted at

はじめに

JavaでGoogle Cloud Storageのオブジェクトリストを取得する方法です。

認証まわりとか、特定のディレクトリのみ取得とかのシンプルな方法を探すのに苦労しました :tired_face:

build.gradle

google-cloud-storageだけでOKです。

build.gradle
apply plugin: 'java'
apply plugin: 'application'

repositories {
  mavenCentral()
}

dependencies {
    compile 'com.google.cloud:google-cloud-storage:0.9.4-beta'
}

mainClassName = "GCSList"

run {
    if (project.hasProperty('args')) {
        args project.args.split('\\s+')
    }
}

コード

特定のディレクトリ配下のオブジェクトに一覧を出力するコードです。

コマンドライン引数でサービスアカウントのJSON Keyのパスを指定できるようになってます。
引数がなければデフォルトのアカウントを使うようになっています。1

src/main/java/GCSList.java
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

import java.io.*;
import java.util.Iterator;

public class GCSList {
    private static final String BUCKET = "mybucket";
    private static final String PREFIX = "dir1/dir2/";

    public static void main(String args[]) throws IOException {
        Storage storage;
        if (args.length > 0) {
            storage = getStorageFromJsonKey(args[0]);
        } else {
            storage = StorageOptions.getDefaultInstance().getService();
        }

        Bucket bucket = storage.get(BUCKET);

        // 特定のディレクトリのみに絞る
        Storage.BlobListOption option = Storage.BlobListOption.prefix(PREFIX);

        Page<Blob> blobs = bucket.list(option);
        Iterator<Blob> blobIterator = blobs.iterateAll();

        while (blobIterator.hasNext()) {
            System.out.println(blobIterator.next().getName());
        }
    }

    private static Storage getStorageFromJsonKey(String key) throws IOException {
        return StorageOptions.newBuilder()
                .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(key)))
                .build()
                .getService();
    }
}

実行

JSON Keyを使う場合

$ ./gradlew run -Pargs="/path/to/key.json"

使わない場合

$ ./gradlew run

おわりに

今回のコードはこちらにあります :pencil:
https://github.com/nownabe/examples/tree/master/list-gcs-java


  1. gcloud auth loginとかするやつ 

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6