Work with Amazon S3 - Amazon SDK for Java 2.x
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Work with Amazon S3

This section provides examples of programming with Amazon Simple Storage Service (S3) using the Amazon SDK for Java 2.x.

The following examples include only the code needed to demonstrate each technique. The complete example code is available on GitHub. From there, you can download a single source file or clone the repository locally to get all the examples to build and run.

Note

From version 2.18.x and onward, the Amazon SDK for Java 2.x uses virtual host-style addressing when including an endpoint override. This applies as long as the bucket name is a valid DNS label.

Call the forcePathStyle method with true in your client builder to force the client to use path-style addressing for buckets.

The following example shows a service client configured with an endpoint override and using path-style addressing.

S3Client client = S3Client.builder() .region(Region.US_WEST_2) .endpointOverride(URI.create("https://s3.us-west-2.amazonaws.com")) .forcePathStyle(true) .build();

Use access points or Multi-Region Access Points

After Amazon S3 access points or Multi-Region Access Points are set up, you can call object methods, such as putObject and getObject and provide the access point identifier instead of a bucket name.

For example, if an access point ARN identifier is arn:aws:s3:us-west-2:123456789012:accesspoint/test, you can use the following snippet to call the putObject method.

Path path = Paths.get(URI.create("file:///temp/file.txt")); s3Client.putObject(builder -> builder .key("myKey") .bucket("arn:aws:s3:us-west-2:123456789012:accesspoint/test") , path);

In place of the ARN string, you can also use the bucket-style alias of the access point for the bucket parameter.

To use Multi-Region Access Point, replace the bucket parameter with the Multi-Region Access Point ARN that has the following format.

arn:aws:s3::account-id:accesspoint/MultiRegionAccessPoint_alias

Add the following Maven dependency to work with Multi-Region Access Points using the SDK for Java. Search maven central for the latest version.

<dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>auth-crt</artifactId> <version>VERSION</version> </dependency>