使用 AWS SDK for Java 获取对象

博客介绍了使用AWS SDK for Java获取对象的方法,包括所需的maven包,还阐述了通过该SDK下载和上传对象的操作。下载时,Amazon S3会返回对象元数据和输入流,上传则给出创建文本字符串和文件对象的示例,最后附上官网Java连接S3的案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 AWS SDK for Java 获取对象

使用的maven包是

     	<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.347</version>
        </dependency>

通过AWS SDK for Java下载某个对象

  • 当您通过AWS SDK for Java下载某个对象时,Amazon S3 将返回该对象的所有元数据以及从中读取该对象
    的内容的输入流。
  • 下面的例子通过三种方式从 Amazon S3 存储桶中检索对象:作为完整的对象、作为来自该对象的一系列字
    节以及作为包含被覆盖的响应标头值的完整对象。

最后附上官网自带的使用java连接S3的案例demo。

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.amazonaws.services.s3.model.S3Object;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-
public class AwsS3Demo {


    public static void main(String[] args) throws IOException {
        String clientRegion = "*** Client region ***";
        String bucketName = "*** Bucket name ***";
        String key = "*** Object key ***";
        S3Object fullObject = null, objectPortion = null, headerOverrideObject = null;

        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // Get an object and print its contents.
            System.out.println("Downloading an object");
            fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
            System.out.println("Content-Type: " +  fullObject.getObjectMetadata().getContentType());
            System.out.println("Content: ");
            displayTextInputStream(fullObject.getObjectContent());

            // Get a range of bytes from an object and print the bytes.
            GetObjectRequest rangeObjectRequest = new GetObjectRequest(bucketName, key).withRange(0,9);
            objectPortion = s3Client.getObject(rangeObjectRequest);
            System.out.println("Printing bytes retrieved.");
            displayTextInputStream(objectPortion.getObjectContent());


          // Get an entire object, overriding the specified response headers, and print the object's content.
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
                    .withCacheControl("No-cache")
                    .withContentDisposition("attachment; filename=example.txt");
            GetObjectRequest getObjectRequestHeaderOverride = new
                    GetObjectRequest(bucketName, key)
                    .withResponseHeaders(headerOverrides);
            headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);

            displayTextInputStream(headerOverrideObject.getObjectContent());
        } catch(AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch(SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        } finally {
            // To ensure that the network connection doesn't remain open, close any open input streams.
            if(fullObject != null) {
                fullObject.close();
            }
            if(objectPortion != null) {
                objectPortion.close();
            }
            if(headerOverrideObject != null) {
                headerOverrideObject.close();
            }
        }
    }


    /**
     * @param input
     * @throws IOException
     */
    private static void displayTextInputStream(InputStream input) throws IOException {
        // Read the text input stream one line at a time and display each line.
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println();
    }

使用 AWS SDK for Java 上传对象

Example:

  • 以下示例将创建两个对象。第一个对象将一个文本字符串作为数据,第二对象是一个文件。
  • 该示例通过在对 AmazonS3Client.putObject() 的调用中直接指定存储桶名称、对象键和文本数据来创建第一个对象。该示例通过使用指定存储桶、对象键和文件路径的 PutObjectRequest 来创建第二个对象。PutObjectRequest 还指定 ContentType 标头和标题元数据。
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.io.IOException;


public class UploadObjectS3Demo {
    public static void main(String[] args) throws IOException {
        String clientRegion = "*** Client region ***";
        String bucketName = "*** Bucket name ***";
        String stringObjKeyName = "*** String object key name ***";
        String fileObjKeyName = "*** File object key name ***";
        String fileName = "*** Path to file to upload ***";
        try {
            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withRegion(clientRegion)
                    .withCredentials(new ProfileCredentialsProvider())
                    .build();

            // Upload a text string as a new object.
            s3Client.putObject(bucketName, stringObjKeyName, "Uploaded String Object");
            
            // Upload a file as a new object with ContentType and title specified.
            PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, new
                    File(fileName));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("plain/text");
            metadata.addUserMetadata("x-amz-meta-title", "someTitle");
            request.setMetadata(metadata);
            s3Client.putObject(request);
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon S3 couldn't process
            // it, so it returned an error response.
            e.printStackTrace();
        } catch (SdkClientException e) {
            // Amazon S3 couldn't be contacted for a response, or the client
            // couldn't parse the response from Amazon S3.
            e.printStackTrace();
        }
    }
}
### AWS SDK for Java 使用指南与下载 AWS SDK for Java 提供了一种简单而强大的方式来通过编程访问 Amazon Web Services (AWS)。以下是关于如何获取使用SDK 的详细介绍。 #### 下载 AWS SDK for Java 官方的 AWS SDK for Java 版本 2 可以从以下地址获得: - **GitCode 地址**: [https://gitcode.com/gh_mirrors/aw/aws-sdk-java-v2](https://gitcode.com/gh_mirrors/aw/aws-sdk-java-v2)[^1] - **GitHub 地址**: [https://github.com/aws/aws-sdk-java-v2](https://github.com/aws/aws-sdk-java-v2)[^3] 可以通过克隆仓库或者直接下载 ZIP 文件的方式将其安装到本地环境中。 #### Maven 配置 如果正在使用 Maven 构建项目,则可以在 `pom.xml` 文件中添加如下依赖项以便集成 AWS SDK for Java: ```xml <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>2.17.298</version> <type>pom</type> <scope>import</scope> </dependency> ``` 注意版本号应替换为你所需的最新稳定版[^4]。 #### 基础配置与初始化 为了能够成功调用 AWS API,需先完成必要的设置工作。这通常涉及创建客户端实例以及提供认证凭证。下面是一个简单的 S3 客户端初始化例子: ```java // 导入所需类库 import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; public class AwsSdkExample { public static void main(String[] args) { Region region = Region.US_EAST_1; // 设置区域 S3Client s3 = S3Client.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create()) .build(); System.out.println("S3 client created successfully."); } } ``` 此代码片段展示了如何基于默认配置文件中的凭据建立一个指向特定地区的 S3 客户端对象[^2]。 #### 更多功能支持 除了基本操作外,新版 SDK 还引入了一些增强特性,比如允许自定义 HTTP 实现方法等高级选项[^3]。这些改进使得开发者可以更加精细地控制请求行为并优化性能表现。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值