将 AWS s3 文件读取为 Java 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28568635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:26:14  来源:igfitidea点击:

Read AWS s3 File to Java code

javaamazon-web-servicesamazon-s3

提问by Edamame

I tried to read a file from AWS s3 to my java code:

我试图从 AWS s3 读取文件到我的 java 代码:

  File file = new File("s3n://mybucket/myfile.txt");
  FileInputStream fileInput = new FileInputStream(file);

Then I got an error:

然后我得到一个错误:

java.io.FileNotFoundException: s3n:/mybucket/myfile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:146)

java.io.FileNotFoundException: s3n:/mybucket/myfile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:146)



Is there a way to open/read a file from AWS s3? Thanks a lot!

有没有办法从 AWS s3 打开/读取文件?非常感谢!

采纳答案by tedder42

The 'File' class from Java doesn't understand that S3 exists. Here's an example of reading a file from the AWS documentation:

Java 中的“文件”类不了解 S3 的存在。以下是从 AWS 文档中读取文件的示例

AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());        
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, key));
InputStream objectData = object.getObjectContent();
// Process the objectData stream.
objectData.close();

回答by Enigo

In 2019 there's a bit more optimal way to read a file from S3:

在 2019 年,有一种更好的方法可以从 S3 读取文件:

private final AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard().build();

private Collection<String> loadFileFromS3() {
    try (final S3Object s3Object = amazonS3Client.getObject(BUCKET_NAME,
                                                            FILE_NAME);
         final InputStreamReader streamReader = new InputStreamReader(s3Object.getObjectContent(), StandardCharsets.UTF_8);
         final BufferedReader reader = new BufferedReader(streamReader)) {
        return reader.lines().collect(Collectors.toSet());
    } catch (final IOException e) {
        log.error(e.getMessage(), e)
        return Collections.emptySet();
    }
}