[英]Delete all objects from a directory in google storage bucket using cloud storage options
I'm using cloud storage options from google cloud to manage data in a GCP bucket.我正在使用来自谷歌云的云存储选项来管理 GCP 存储桶中的数据。 I've a directory under which I want to delete all the objects before I start writing new objects.
我有一个目录,我想在开始编写新对象之前删除该目录下的所有对象。 sample directory: gs://bucket-name/directory1/subdirectory/
示例目录:gs://bucket-name/directory1/subdirectory/
I'm able to delete a single object using the following code, but how do I get list of all the objects in a directory and delete all of them?我可以使用以下代码删除单个 object,但如何获取目录中所有对象的列表并删除所有对象?
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class DeleteObject {
public static void deleteObject(String projectId, String bucketName, String objectName) {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The ID of your GCS object
// String objectName = "your-object-name";
Storage storage =
StorageOptions.newBuilder().setProjectId(projectId).build().getService();
storage.delete(bucketName, objectName);
System.out.println("Object " + objectName + " was deleted from " + bucketName);
}
}
Iterate over objects
in the bucket
with a prefix of the directory name.使用目录名称的前缀迭代
bucket
中的objects
。
See the following snippet:请参阅以下代码段:
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Page<Blob> blobs =
storage.list(
bucketName,
Storage.BlobListOption.prefix(directoryPrefix), // directoryPrefix is the sub directory.
Storage.BlobListOption.currentDirectory());
for (Blob blob : blobs.iterateAll()) {
blob.delete(Blob.BlobSourceOption.generationMatch());
}
References:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.