I would like to write a file to GCS bucket, and if it exists just overwrite it.
The python docs show it's possible to overwrite the content of a blob using blob.upload_from_string('New contents!')
.
For Java I only found delete/create (update just updates the metadata).
So my code currently do this:
public boolean doesObjectExist(String bucketName, String objectName) {
Blob object = storage.get(bucketName, objectName);
return object != null;
}
public void uploadObject(String bucketName, String objectName, String content) {
BlobId blobId = BlobId.of(bucketName, objectName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
if (doesObjectExist(bucketName, objectName)){
storage.delete(bucketName, objectName);
}
storage.create(blobInfo, content.getBytes(UTF_8));
}
Is there something overwrite via the Java API?
You can't update the Blob content (even in Python!). You can only create, delete, read. You can't move, you can't rename. These 2 operations perform a create (with the new name/destination) and a delete (the old name).
So now, how you overwrite the existing content: simply write the content. If it exists, it will be replaced. If you have activated the versioning on the bucket, the previous version is kept as noncurrent version, and the uploaded content is served as live version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With