1

I have a com.google.cloud.storage.Blob object. I have been able to download and upload just fine with this object in my java code, but I wanted to check if something exists before starting a process.In a nutshell here is the part of my code giving me issues.

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class Function implements BackgroundFunction<GcsEvent> {
    public void accept(GcsEvent event, Context context) {
        String bucketname = "my_bucket";
        String blob_path = "path/to/my/object.jpg";
        Storage storage = StorageOptions.newBuilder().setProjectId("my_project_id").build().getService();
        Blob b = storage.get(BlobId.of(bucketname, blob_path));
        // this is where the null pointer exception occurs
        boolean exists = b.exists();
        if (exists) {
            //do something
        }
    }
}

Eclipse doesn't seem to catch it in the IDE. and the examples seem to follow this layout as well. Would anyone know what is going on?

I am running on a Linux environment machine. (it failed in cloud function as well). I am using the Java 11 runtime.

connor
  • 51
  • 5
  • 1
    Your first source should always be the official documentation. In that case the [documentation of the get method of Storage](https://googleapis.dev/java/google-cloud-clients/0.97.0-alpha/com/google/cloud/storage/Storage.html#get-com.google.cloud.storage.BlobId-) quite clearly states: "Returns the requested blob or **null if not found.** " – OH GOD SPIDERS May 18 '22 at 15:23

1 Answers1

2

I feel silly. I found out that storage.get(BlobId.of(bucketname, blob_path)); will return null if it can't find the object. instead of using b.exists(), one should check if it is null with if (b != null) { //do stuff }.

connor
  • 51
  • 5