Skip to content

Amazon Web Services

Robin Drew edited this page Feb 27, 2025 · 6 revisions

You can interact with AWS using their Java API. It covers most operations you might want to execute on AWS.

S3

The Simple Storage Service is a database. It is a fully elactic (scalable) object store.

Buckets

Objects are stored in buckets. A bucket is a mapping from String keys to Object values.

// Create a simple client
S3Client client = S3Client.builder().httpClientBuilder(ApacheHttpClient.builder()).build();

// Create a bucket
// (String bucketName)
client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build());

// Delete a bucket
// (String bucketName)
client.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());

// Put data in the bucket
// (String bucketName, String key, RequestBody value)
client.putObject(PutObjectRequest.builder().bucket(bucketName).key(key).build(), value);

// Get data from a bucket
// (String bucketName, String key)
ResponseInputStream<GetObjectResponse> response = client.getObject(GetObjectRequest.builder().bucket(bucketName).key(key).build());

// Delete data in a bucket
// (String bucketName, String key)
client.deleteObject(DeleteObjectRequest.builder().bucket(name).key(key).build());

Store Data

The operation to store data putObject() requires converting the data to a RequestBody object.

// There are a number of static utility methods to create a request body
RequestBody.empty();
RequestBody.fromBytes(byte[] bytes);
RequestBody.fromString(String text); // UTF-8
RequestBody.fromString(String text, Charset charset);
RequestBody.fromInputStream(InputStream stream, int length);
RequestBody.fromFile(File file);
RequestBody.fromFile(Path path);

Retrieve Data

When calling getObject() you can a couple of options of the response format:

// You can stream the response bytes back (streaming is always useful if the data is large)
try (ResponseInputStream<GetObjectResponse> response = client.getObject(request)) {
   ... handle response ...
}

// Alternatively you can read the response as bytes in to memory and the convert ...
ResponseBytes<GetObjectResponse> response = client.getObjectAsBytes(request);
response.asByteArray();
response.asUtf8String();
response.asString(UTF_8);
response.asByteBuffer();
response.asInputStream();

Clone this wiki locally