How to read a file from Google Cloud Storage in Java

后端 未结 2 803
天命终不由人
天命终不由人 2020-12-03 08:32

I would like to read a file from Google Cloud storage using Java. The below link was not helpful as I dont use HttpServletRequest and HttpServletResponse.

Reading i

相关标签:
2条回答
  • 2020-12-03 09:00

    The simplest way to accomplish this is to use Google's google-cloud Java library. Downloading will look something like this:

    String PROJECT_ID = "my-project";
    String PATH_TO_JSON_KEY = "/path/to/json/key";
    String BUCKET_NAME = "my-bucket";
    String OBJECT_NAME = "my-object";
    
    StorageOptions options = StorageOptions.newBuilder()
                .setProjectId(PROJECT_ID)
                .setCredentials(GoogleCredentials.fromStream(
                        new FileInputStream(PATH_TO_JSON_KEY))).build();
    
    Storage storage = options.getService();
    Blob blob = storage.get(BUCKET_NAME, OBJECT_NAME);
    ReadChannel r = blob.reader();
    
    0 讨论(0)
  • 2020-12-03 09:06

    Read this GCloud doc for more info.

    Your code should be:

    Storage storage = StorageOptions.newBuilder()
                .setProjectId(projectId)
                .setCredentials(GoogleCredentials.fromStream(new FileInputStream(serviceAccountJSON)))
                .build()
                .getService();
    Blob blob = storage.get(BUCKET_URL, OBJECT_URL);
    String fileContent = new String(blob.getContent());
    
    0 讨论(0)
提交回复
热议问题