如何使用Java的Google Cloud Client库列出文件和文件夹

时间:2018-08-09 19:36:31

标签: java google-cloud-storage

是否可以使用Java的Google Cloud Client库列出文件和文件夹?

try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("demo")){       
     Path path = fs.getPath("/");
}

在这里我需要列出“演示”存储桶中的文件夹和子文件夹(和文件)。

1 个答案:

答案 0 :(得分:1)

您可以在此处查看Google的参考文献:Cloud Storage Client Libraries

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public static void printGCSItems(){

    Set folders = new HashSet();
    Set files = new HashSet();

    // Instantiates a client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get the bucket
    Bucket bucket = storage.get("demo");

    Page<Blob> blobs = bucket.list();
    for (Blob blob : blobs.iterateAll()) {
       // Gets the path of the object
        String path = blob.getName();

        if (isDir(path) && !folders.contains(path)){ // If the object is a folder, then add it to folders set
            folders.add(path);
        } else { // If the object isn't a folder, then extract the parent path and add it to folders set
            String parentDir = getParentDir(path);
            if (!folders.contains(parentDir)){
                folders.add(parentDir);
                System.out.println(parentDir);
            }
            files.add(path);
        }
        System.out.println(path);
    }
}

public static boolean isDir(String path){
    return path.endsWith("/");
}

public static String getParentDir(String path){
    return path.substring(0, path.lastIndexOf("/") + 1);
}