gpt4 book ai didi

java - 如何使用 S3AsyncClient 从 S3 读取 JSON 文件

转载 作者:行者123 更新时间:2023-11-30 01:56:44 25 4
gpt4 key购买 nike

我不知道如何将 JSON 文件作为 String 从 S3 读取到内存中。

我发现的示例调用 getObjectContent() 但这不适用于我从 S3AsyncClient 获取的 GetObjectResponse

我实验的代码是来自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 获取实际的 JSON 内容?

最佳答案

响应转换为字节后,可以转换为字符串:

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();
});

关于java - 如何使用 S3AsyncClient 从 S3 读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54202726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com