Amzon s3 Java API列出基目录的子目录

时间:2016-11-30 09:14:00

标签: java amazon-s3

我遵循亚马逊关键结构:

as3/basedir/dir-1/file-1.txt
as3/basedir/dir-2/file-2.txt
as3/basedir/dir-3/file-3.txt
as3/basedir/dir-4/file-4.txt
as3/basedir/dir-5/file-5.txt
as3/basedir/dir-6/dir-6-1/file-6.txt
as3/basedir/dir-7/dir-7-1/file-7.txt
as3/basedir/dir-8/dir-8-1/file-8.txt
as3/basedir/dir-9/dir-9-1/file-9.txt
as3/basedir/dir-10/dir-10-1/file-10.txt

获取输出为List,即子目录名称。

=> 1.请求密钥前缀= /as3/basedir/

Output List: [dir-1,dir-2,dir-3,dir-4,dir-5]

=> 2.请求密钥前缀= /as3/basedir/dir-6/

Output List: [dir-6-1]

1 个答案:

答案 0 :(得分:0)

遵循Java方法impl解决我的上述问题:

    /**
     * Listing just the sub dirs in an s3 bucket
     * @param prefix
     * @param limit
     * @return list of subdirs
     */
    public List<String> getSubDirInAS3(String prefix,Integer limit) {
        final String DELIMITER ="/";
        if (!prefix.endsWith(DELIMITER)) {
            prefix += DELIMITER;
        }
        List<String> paths = new ArrayList<String>();
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
                .withBucketName(config.getBucketName()).withPrefix(prefix)
                .withMaxKeys(limit).withDelimiter(DELIMITER);
        ObjectListing currentListing = client.listObjects(listObjectsRequest);

        while (currentListing == null || currentListing.isTruncated()) {
            currentListing = client.listNextBatchOfObjects(currentListing);
            paths.addAll(currentListing.getCommonPrefixes());
            //currentListing.setMarker(currentListing.getNextMarker());
        }
        return paths;
    }