1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ListObjectsV2Request(AWS SDK for Java)でS3のファイル一覧を取得する

Last updated at Posted at 2018-10-19

概要

  • ファイルの一覧を取得するにはListObjectsV2Requestを利用する
    • ListObjectsV2Requestは一回のリクエストですべての一覧を返さない場合がある
      • ListObjectsV2Result#isTruncatedtrueの場合はすべてのファイル一覧を取得できていない
        • ListObjectsV2Request#setContinuationTokenListObjectsV2Result#getNextContinuationTokenを渡して、再度取得する必要がある。

すべてのファイル一覧を取得するIterator

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import lombok.val;

import java.util.*;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

class S3ObjectSummaryIterator implements Iterator<S3ObjectSummary> {

    private final AmazonS3 client;
    private final ListObjectsV2Request request;
    private final Queue<S3ObjectSummary> summaries = new LinkedList<>();
    private boolean isTruncated = false;

    S3ObjectSummaryIterator(AmazonS3 client, ListObjectsV2Request request) {
        this.client = client;
        this.request = request;
        fetch();
    }

    private void fetch() {
        val result = this.client.listObjectsV2(this.request);
        summaries.addAll(result.getObjectSummaries());
        this.isTruncated = result.isTruncated();
        if (result.isTruncated()) {
            request.setContinuationToken(result.getNextContinuationToken());
        }
    }

    @Override
    public boolean hasNext() {
        if (summaries.isEmpty() && isTruncated) {
            fetch();
        }
        return !summaries.isEmpty();
    }

    @Override
    public S3ObjectSummary next() {
        return summaries.poll();
    }

    public static Stream<S3ObjectSummary> stream(AmazonS3 client, ListObjectsV2Request request) {
        val iterator = new S3ObjectSummaryIterator(client, request);
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);
    }

}

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?