Snippet Java for S3

With snippet Java for S3, you can free your mind

  1. Remove a S3 folder

    AmazonS3 s3Client = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
    s3Client.setEndpoint("s3-ap-northeast-1.amazonaws.com");
    String bucketName = "mybucket";
    String prefix= "mykey/";
    // prefix with '/' character to ignore folder mykey in list object
    List keys = new ArrayList();
    KeyVersion keyVersion = null;
    ObjectListing list = s3Client.listObjects(bucketName, prefix);
    do {
      List summaries = list.getObjectSummaries();
      for (S3ObjectSummary summary : summaries) {
        keyVersion = new KeyVersion(summary.getKey());
        keys.add(keyVersion);
      }
      list = s3.listNextBatchOfObjects(list);
    } while (list.isTruncated());
    if (keys.size() > 0) {
      DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
      s3.deleteObjects(deleteObjectsRequest.withKeys(keys));
    }
    
  2. Save object to S3

    File file = new File(localPath);
    s3.putObject(new PutObjectRequest(bucketName, prefix, file));
    
  3. Listing subdirectory in an S3 folder

    String delimiter = "/"; // the delimiter for condensing common prefixes in the returned listing results
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
        .withBucketName(bucketName).withPrefix(prefix)
        .withDelimiter(delimiter);
    ObjectListing objects = s3Client.listObjects(listObjectsRequest);
    List listSubdirectory = objects.getCommonPrefixes();
    
  4. Listing file in an S3 folder ignore subdirectory and recursive

    String delimiter = "/"; // the delimiter for condensing common prefixes in the returned listing results
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
        .withBucketName(bucketName).withPrefix(prefix)
        .withDelimiter(delimiter);
    ObjectListing objects = s3Client.listObjects(listObjectsRequest);
    List listFile = objects.getObjectSummaries();
    

Comments

Popular posts from this blog

Reduce TIME_WAIT Socket Connections