将AWS s3文件读取为Java代码

时间:2015-02-17 18:34:23

标签: java amazon-web-services amazon-s3

我尝试将AWS s3中的文件读取到我的java代码中:

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

然后我收到了一个错误:

java.io.FileNotFoundException:s3n:/mybucket/myfile.txt(没有这样的文件或目录)     at java.io.FileInputStream.open(Native Method)     在java.io.FileInputStream。(FileInputStream.java:146)


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

6 个答案:

答案 0 :(得分:20)

'文件' Java中的类并不了解S3存在。 Here's an example of reading a file from the AWS documentation

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

答案 1 :(得分:2)

如果文件的内容是字符串,则可以使用getObjectAsString。否则,您可以在getObjectContent()上使用IOUtils.toByteArray将文件内容读入字节数组。

显然,这些方法最适合用于小尺寸S3对象,这些对象很容易装入内存。

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

private String loadStringFromS3() {
    try {
        return amazonS3Client.getObjectAsString(BUCKET_NAME, FILE_NAME);
    } catch (final IOException e) {
        log.error(e.getMessage(), e)
        return null;
    }
}

private byte[] loadDataFromS3() {
    try (final S3Object s3Object = amazonS3Client.getObject(BUCKET_NAME, FILE_NAME)) {
        return IOUtils.toByteArray(s3Object.getObjectContent());
    } catch (final IOException e) {
        log.error(e.getMessage(), e)
        return null;
    } finally {
        IOUtils.closeQuietly(object, log);
    }
}

答案 2 :(得分:2)

我们也可以使用 software.amazon.awssdk:s3

 //Assuming the credentials are read from Environment Variables, so no hardcoding here

    S3Client client = S3Client.builder()
                        .region(regionSelected)
                        .build();
    
    GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                    .bucket(bucketName)
                    .key(fileName)
                    .build();
    
    ResponseInputStream<GetObjectResponse> responseInputStream = client.getObject(getObjectRequest);

    InputStream stream = new ByteArrayInputStream(responseInputStream.readAllBytes());
    
    
    System.out.println("Content :"+ new String(responseInputStream.readAllBytes(), StandardCharsets.UTF_8));

答案 3 :(得分:0)

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

答案 4 :(得分:0)

在Java中读取S3文件的步骤可以是:

  1. 创建AmazonS3Client。
  2. 使用存储桶名称和密钥创建S3Object。
  3. 使用S3Object创建缓冲区读取器并逐行读取文件。

1 >>>

    BasicAWSCredentials awsCreds = new BasicAWSCredentials("accessKey", "secretKey");
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion("region_name_here").build();  

2 >>>

   S3Object object = s3Client.getObject(new GetObjectRequest("bucketName", "key"));

3 >>>

   BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));

    String s = null;
    while ((s = reader.readLine()) != null)
    {
        System.out.println(s);
        //your business logic here
    }

谢谢。

答案 5 :(得分:0)

这是我的解决方案。我正在使用弹簧靴 2.4.3

创建亚马逊 s3 客户端

AmazonS3 amazonS3Client = AmazonS3ClientBuilder
                .standard()
                .withRegion("your-region")
                .withCredentials(
                        new AWSStaticCredentialsProvider(
                            new BasicAWSCredentials("your-access-key", "your-secret-access-key")))
                .build();

创建一个亚马逊转账客户端

TransferManager transferManagerClient = TransferManagerBuilder.standard()
                .withS3Client(amazonS3Client)
                .build();

/tmp/{your-s3-key}中创建一个临时文件,以便我们可以将我们下载的文件放在这个文件中。

File file = new File(System.getProperty("java.io.tmpdir"), "your-s3-key"); 

try {
    file.createNewFile(); // Create temporary file
} catch (IOException e) {
    e.printStackTrace();
}

file.mkdirs();  // Create the directory of the temporary file

然后,我们使用传输管理器客户端

从 s3 下载文件
// Note that in this line the s3 file downloaded has been transferred in to the temporary file that we created
Download download = transferManagerClient.download(
               new GetObjectRequest("your-s3-bucket-name", "your-s3-key"), file); 

// This line blocks the thread until the download is finished
download.waitForCompletion();  

现在 s3 文件已成功传输到我们创建的临时文件中。我们可以得到临时文件的InputStream。

InputStream input = new DataInputStream(new FileInputStream(file));

因为不再需要临时文件,我们就删除它。

file.delete();