java - 如何使用适用于 Java 的 Google Cloud 客户端库列出文件和文件夹
问题描述
有没有办法使用适用于 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);
}
推荐阅读
- visual-studio - Building only particular project in the Visual Studio solution
- python - 通过 python 脚本 SSL 连接在 Jenkins 中构建作业
- bash - 前置然后重定向
- microsoft-graph-api - MS Graph API 可以在 (UTC+5:30) 时区读取 Outlook 的电子邮件吗?
- flutter - 如何转换列表
列出 飘飘然 - javascript - JSON:数据未显示在网页中
- java - 为什么我会收到“线程“主”java.lang.NoClassDefFoundError:org/lwjgl/LWJGLException 中的异常”错误?
- c++ - 如何使用 C++ 更改多维数组的内存布局
- android - Intent.getStringExtra() 在 Kotlin Android 中返回 null
- wordpress - 为什么 get_posts() 返回空数据?