使用云存储选项从 google 存储桶中的目录中删除所有对象

Delete all objects from a directory in google storage bucket using cloud storage options

我正在使用来自 google 云的云存储选项来管理 GCP 存储桶中的数据。我有一个目录,我想在开始编写新对象之前删除该目录下的所有对象。 示例目录:gs://bucket-name/directory1/subdirectory/

我可以使用以下代码删除单个对象,但如何获取目录中所有对象的列表并删除所有对象?

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);
     }
   }

bucket 中使用目录名称的前缀迭代 objects

请参阅以下代码段:

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());
}

参考文献: