Fetching file from google storage bucket

I am trying to fetch a file from google storage bucket. The method takes two parameters the "fileName" and "bucketName" as input and should return the required file. I have used the Storage class get method to fetch the data blob. My attempt is given below.

@Autowired
private Storage storage;

static String FILEPATH = "../../../resources/static/filename.json";
static File file = new File(FILEPATH);

public File fetchFile(String fileName, String bucketName) {
  try {
    Blob dataBlob = storage.get(BlobId.of(bucketName, fileName));
    OutputStream os = new FileOutputStream(file);
    os.write(dataBlob.getContent());
    os.close();
    log.info("File fetched successfully");
    return file;
  } catch (Exception e) {
    String msg = "Error fetching file "+fileName+" from Storage ";
    log.error(msg);
    e.printStackTrace();
    throw new RuntimeException(msg);
  }
}

The error I am getting is:

java.io.FileNotFoundException: ../../../resources/static/filename.json (No such file or directory)

I am new to spring boot and GCP.

1 answer

  • answered 2021-06-16 18:11 guillaume blaquiere

    No relation with Google Cloud here. it's pure java error. Use absolute path for your file location, not a java project relative path.


    EDIT 1

    Works perfectly for me

        public static void main(String[] args) {
    
            Storage storage =  StorageOptions.getDefaultInstance().getService();
            String FILEPATH = "/Absolute/Path/to/file";
            File file = new File(FILEPATH);
    
                try {
                    Blob dataBlob = storage.get(BlobId.of("MyBucket", "MyFile"));
                    OutputStream os = new FileOutputStream(file);
                    os.write(dataBlob.getContent());
                    os.close();
                    System.out.println("File fetched successfully");
                } catch (Exception e) {
                    String msg = "Error fetching file from Storage ";
                    System.out.println(msg);
                    e.printStackTrace();
                }
    }