java - 如何使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹

标签 java google-cloud-storage

是否可以使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹?

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

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

最佳答案

您可以在 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);
}

关于java - 如何使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774611/

相关文章:

java - 如何在java中获取插入MongoDB的最后一个特定文档

java - 如何通过espresso UI测试初始化​​presenter的可为空变量以避免NPE

java - 未定义的反射和注释

redirect - GCP - 静态托管 - 重定向到/index.html

firebase - 在 Firestore 中创建对 Cloud Storage 文档的引用

google-app-engine - 如何在 GAE 中接收配额警报

java - 确保绘制(paint)的绳子不会离开可见区域?

java - Java中如何锁定序列化?

python-3.x - google.cloud storage python api在指定位置创建桶

google-cloud-storage - 如何通过扩展设置全局 mime 类型?