LoginSignup
1
4

More than 5 years have passed since last update.

Kotlin で AWS の S3 の特定のフォルダにあるファイルのURL一覧を取得する

Posted at

Kotlin で AWS の S3 の特定のフォルダにあるファイルのURL一覧を取得したときのコードです。 Kotlin で AWS を操作したい人の参考になれば幸いです。

Gradle

Gradle では AWS S3 のライブラリを記述します。

buildscript {
    ext.kotlin_version = '1.2.40'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'com.example'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin'


repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    // https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk
    compile group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.11.319'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Credential

Kotlin の Credential と S3Client を作るコードです。 この部分は使いまわせます。

package com.example.s3

import com.amazonaws.auth.AWSStaticCredentialsProvider
import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.AmazonS3ClientBuilder
import java.util.*

object Owner {
    val accessKey = "..."
    val secretKey = "..."
    val id = "..."

    fun createFilter(): Filter {
        return Filter().
                withName("owner-id").
                withValues(id)
    }
}

val credential = BasicAWSCredentials(Owner.accessKey, Owner.secretKey)

val s3client = AmazonS3ClientBuilder.standard().
        withRegion(Regions.AP_SOUTH_1).
        withCredentials(AWSStaticCredentialsProvider(credential)).
        build()

ファイルのURLを出す部分のコード

私の場合、上のコードに加え、こちらのコードも同じファイルに記述して実行しました。

fun main(vararg s: String) {
    val ol = s3client.listObjects("bucket-name", "demo/folder/path")
    for (objectSummary in ol.objectSummaries) {
        if (!objectSummary.key.endsWith('/')) {
            println(
                    s3client.getUrl("bucket-name", objectSummary.key).toString().
                            replace(
                                "bucket-name.s3.ap-south-1.amazonaws.com/",
                                "s3.ap-south-1.amazonaws.com/bucket-name/").
                            replace("%29", ")").
                            replace("%28", "(").
                            replace("%20", "+"))
        }
    }
}

注意点

  • ObjectSummary クラス の key/ で終わっているか否かで、 フォルダなのかファイルなのかをチェックしています。
  • 有効なリンクにするために、数か所でreplaceを実行しています。 なぜ有効なリンクにならなかったのかはよくわかりません。
    • ドメイン, ), (, + について replace しています。
    • ほかにも replace するべきところはあるかもしれません。
    • ファイルの名前に (, ), がなければこの処理は必要ありません。
1
4
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
4