我在云存储桶中有一个名为“myfolder”的文件夹。它有像.log,b.log等文件。如何以编程方式从存储桶中的文件夹中删除所有这些文件。
我想要一些java示例代码来完成它。
答案 0 :(得分:2)
我通过从我们的生产代码库中获取片段来构建此示例。请注意使用setPrefix(folder)
过滤来自存储桶的内容。
所以逻辑是从桶中获取所有内容并根据文件夹名称进行过滤,删除它。
import java.io.IOException;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.*;
public void deleteFolder(String bucketName, String folder) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder();
final GoogleCredential credential = credentialBuilder
.setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId("YourServiceAccountId")
// .setServiceAccountPrivateKeyFromP12File(new File("PrivateKeyFile"))
.build();
Storage storage = new Storage(httpTransport, jsonFactory,
new HttpRequestInitializer() {
public void initialize(HttpRequest request)
throws IOException {
credential.initialize(request);
}
});
// PLEASE NOTE THE USAGE OF setPrefix(folder) TO FILTER ITEMS IN FOLDER
Objects objectsInFolder = storage.objects().list(bucketName).setPrefix(folder).execute();
for(StorageObject object : objectsInFolder.getItems()) {
storage.objects().delete(bucketName, object.getName()).execute();
}
}