Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
Travailler avec des Amazon S3 objets
Un objet Amazon S3 représente un fichier ou un ensemble de données. Chaque objet doit être contenu dans un compartiment.
Note
Bonne pratique
Nous vous recommandons d'activer la règle du AbortIncompleteMultipartUploadcycle de vie sur vos Amazon S3 buckets.
Cette règle indique à Amazon S3 d'interrompre les chargements partitionnés qui ne sont pas terminés après un nombre de jours prédéfini à compter de leur lancement. Lorsque le délai défini est dépassé, Amazon S3 interrompt le chargement, puis supprime les données du chargement inachevé.
Pour plus d'informations, consultez la section Configuration du cycle de vie d'un bucket avec gestion des versions dans le guide de l'Amazon Simple Storage Serviceutilisateur.
Note
Ces extraits de code supposent que vous comprenez le contenu de base et que vous avez configuré les informations d'AWSidentification par défaut à l'aide des informations contenues dans. Configuration de l'accès par authentification unique pour le SDK
Rubriques
Charger un objet
Créez un PutObjectRequestputObject
méthode du S3Client avec un RequestBodyPutObjectRequest
objet. Le compartiment doit exister, sans quoi le service renvoie une erreur.
Importations
import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.waiters.S3Waiter; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
Region region = Region.US_WEST_2; s3 = S3Client.builder() .region(region) .build(); createBucket(s3, bucketName, region); PutObjectRequest objectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(key) .build(); s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000)));
Consultez l'exemple complet
Charger des objets partitionnés
Utilisez la createMultipartUpload
méthode du S3Client pour obtenir un identifiant de téléchargement. Ensuite, utilisez la méthode uploadPart
pour charger chaque partie. Enfin, utilisez la completeMultipartUpload
méthode du S3Client pour demander de fusionner toutes les parties téléchargées et de terminer l'opération de téléchargement. Amazon S3
Importations
import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.waiters.S3Waiter; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
// First create a multipart upload and get the upload id CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() .bucket(bucketName) .key(key) .build(); CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); String uploadId = response.uploadId(); System.out.println(uploadId); // Upload all the different parts of the object UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() .bucket(bucketName) .key(key) .uploadId(uploadId) .partNumber(1).build(); String etag1 = s3 .uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) .eTag(); CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) .uploadId(uploadId) .partNumber(2).build(); String etag2 = s3 .uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) .eTag(); CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); // Finally call completeMultipartUpload operation to tell S3 to merge all // uploaded // parts and finish the multipart operation. CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() .parts(part1, part2) .build(); CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() .bucket(bucketName) .key(key) .uploadId(uploadId) .multipartUpload(completedMultipartUpload) .build(); s3.completeMultipartUpload(completeMultipartUploadRequest);
Consultez l'exemple complet
Supprimer un objet
Créez un DeleteObjectRequestdeleteObject
méthode du S3Client et transmettez-lui le nom du bucket et de l'objet à supprimer. Le compartiment et la clé d'objet spécifiés doivent exister, sans quoi le service renvoie une erreur.
Importations
import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.waiters.S3Waiter; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() .bucket(bucketName) .key(key) .build(); s3.deleteObject(deleteObjectRequest);
Consultez l'exemple complet
Copier un objet
Créez un CopyObjectRequestcopyObject
méthode du S3Client et transmettez l'CopyObjectRequest
Importations
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.S3Exception;
Code
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.S3Exception; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CopyObject { public static void main(String[] args) { final String usage = """ Usage: <objectKey> <fromBucket> <toBucket> Where: objectKey - The name of the object (for example, book.pdf). fromBucket - The S3 bucket name that contains the object (for example, bucket1). toBucket - The S3 bucket to copy the object to (for example, bucket2). """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String objectKey = args[0]; String fromBucket = args[1]; String toBucket = args[2]; System.out.format("Copying object %s from bucket %s to %s\n", objectKey, fromBucket, toBucket); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); copyBucketObject(s3, fromBucket, objectKey, toBucket); s3.close(); } public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { CopyObjectRequest copyReq = CopyObjectRequest.builder() .sourceBucket(fromBucket) .sourceKey(objectKey) .destinationBucket(toBucket) .destinationKey(objectKey) .build(); try { CopyObjectResponse copyRes = s3.copyObject(copyReq); return copyRes.copyObjectResult().toString(); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
Consultez l'exemple complet
Répertorier les objets
Créez un ListObjectsRequestlistObjects
méthode du S3Client et transmettez l'ListObjectsRequest
objet. Cette méthode renvoie un ListObjectsResponse
Importations
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Object; import java.util.List;
Code
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Object; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListObjects { public static void main(String[] args) { final String usage = """ Usage: <bucketName>\s Where: bucketName - The Amazon S3 bucket from which objects are read.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listBucketObjects(s3, bucketName); s3.close(); } public static void listBucketObjects(S3Client s3, String bucketName) { try { ListObjectsRequest listObjects = ListObjectsRequest .builder() .bucket(bucketName) .build(); ListObjectsResponse res = s3.listObjects(listObjects); List<S3Object> objects = res.contents(); for (S3Object myValue : objects) { System.out.print("\n The name of the key is " + myValue.key()); System.out.print("\n The object is " + calKb(myValue.size()) + " KBs"); System.out.print("\n The owner is " + myValue.owner()); } } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // convert bytes to kbs. private static long calKb(Long val) { return val / 1024; } }
Consultez l'exemple complet
Plus d'exemples
La section Exemples de code de ce guide contient d'autres exemples d'utilisation des objets Amazon S3, notamment comment télécharger un objet.