我想使用Java从Google云端存储中读取文件。以下链接没有帮助,因为我不使用HttpServletRequest和HttpServletResponse。
https://developers.google.com/adwords/api/docs/appendix/reports/product-partition-report
还有其他方法可以实现这一目标吗?我正在编写一个简单的独立程序作为POC
答案 0 :(得分:7)
实现此目标的最简单方法是使用Google的google-cloud Java库。下载将如下所示:
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();
答案 1 :(得分:3)
阅读此GCloud doc以获取更多信息。
您的代码应为:
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());