首页 > 解决方案 > 如何使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹

问题描述

有没有办法使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹?

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

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

标签: javagoogle-cloud-storage

解决方案


您可以在此处查看来自 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);
}

推荐阅读