クラスパス上にあるプロパティファイルを読み込むには・・・?
Javaだとクラスパス上にあるリソースを読み込むにはJavaクラスクラス(Class<?>のクラス)の利用するがKotlinだとどうするのかな?と思って調べたもの。
Javaクラスクラスを参照するには、this.javaClass
とすればいいらしい。クラスローダーも.classLoader
でいいみたい。
以下は簡単なクラスパスの通ったディレクトリに置かれたプロパティファイルを読み取るサンプル。
Main.kt
import java.io.File import java.io.InputStreamReader import java.net.URL import java.util.* class PropertiesReadSample1 { fun readProperty() { val prop = Properties() val resource: URL? = this.javaClass.classLoader.getResource("sample.properties") InputStreamReader(resource?.openStream(), "UTF-8").use { inStream -> prop.load(inStream) println("ooo's value is ${prop.getProperty("aaa")}") println("bbb's value is ${prop.getProperty("bbb")}") println("ううう's value is ${prop.getProperty("ううう")}") } } } fun main(args: Array<String>) { PropertiesReadSample1().readProperty() }
sample.properties [UTF-8] (クラスパスの通ったディレクトリに置くこと)
aaa=100 bbb=200 ううう=300
Output
ooo's value is 100 bbb's value is 200 ううう's value is 300
ちょっと脇道に逸れるけど、Propertiesファイルってnative2asciiしなくても大丈夫になってたのね。
参考
Kotlinでクラスオブジェクトを参照する(Javaのクラス名.classの代わり) - Qiita
[Java] getResourceAsStreamの使い方