java - 如何使用 S3AsyncClient 从 S3 读取 JSON 文件
问题描述
我无法弄清楚如何将 JSON 文件从 S3 读取到内存中String
。
我找到的示例调用getObjectContent()
但是这不适用于GetObjectResponse
我从 S3AsyncClient 获得的。
我实验的代码是来自 AWS 的示例代码。
// Creates a default async client with credentials and AWS Region loaded from the
// environment
S3AsyncClient client = S3AsyncClient.create();
// Start the call to Amazon S3, not blocking to wait for the result
CompletableFuture<GetObjectResponse> responseFuture =
client.getObject(GetObjectRequest.builder()
.bucket("my-bucket")
.key("my-object-key")
.build(),
AsyncResponseTransformer.toFile(Paths.get("my-file.out")));
// When future is complete (either successfully or in error), handle the response
CompletableFuture<GetObjectResponse> operationCompleteFuture =
responseFuture.whenComplete((getObjectResponse, exception) -> {
if (getObjectResponse != null) {
// At this point, the file my-file.out has been created with the data
// from S3; let's just print the object version
System.out.println(getObjectResponse.versionId());
} else {
// Handle the error
exception.printStackTrace();
}
});
// We could do other work while waiting for the AWS call to complete in
// the background, but we'll just wait for "whenComplete" to finish instead
operationCompleteFuture.join();
应该如何修改此代码,以便我可以从GetObjectResponse
?
解决方案
响应转换为字节后,它可以转换为字符串:
S3AsyncClient client = S3AsyncClient.create();
GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket("my-bucket").key("my-object-key").build();
client.getObject(getObjectRequest, AsyncResponseTransformer.toBytes())
.thenApply(ResponseBytes::asUtf8String)
.whenComplete((stringContent, exception) -> {
if (stringContent != null)
System.out.println(stringContent);
else
exception.printStackTrace();
});
推荐阅读
- ios - 隐藏时如何删除“PTCardTabBar”后面的空白?
- python - 如果有 2 个外键与 Django Rest Framework 连接同一个表,如何序列化连接的表?
- javascript - 为什么我设置的间隔不能在反应本机应用程序中工作?
- azure - 使用 POSTMAN 获取授权码 - OAuth2.0
- ios - xCode 安装错误 - 无法从 GoogleUtilities.framework 加载 info.plist
- ios - 如何使用 swift 将文件 Doc/pdf/excel 从 iphone 设备上传到后端?
- python - 如何分组并将操作聚合到多个列?
- r - 在 r 中解开数据框的最佳方法
- javascript - JavaScript Async/Await 逻辑表现为同步
- javascript - 在动画将它们从侧面引入之前,我有一个斜线。我该如何摆脱它?