In my Kotlin project in folder resources I has properties file. How I can read content data from this file to Properties object?
I try this:
val fis = FileInputStream("resources/pairs_ids.txt")
prop.load(fis);
logger.info("ETH_BTC_id = " + prop.get("ETH_BTC"))
But I get error:
Exception in thread "main" java.io.FileNotFoundException: resources\pairs_ids.txt (The system cannot find the path specified)
The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.
To read the file we have to use the Java Filereader and set the path of the properties file. FileReader reader=new FileReader("file path"); Then we have to load the File into the properties using the load method.
Reading Properties File in Python The first step is to import the Properties object into our Python program and instantiate it. The next step is to load the properties file into our Properties object. Now, we can read a specific property using get() method or through the index.
what I like to do in this case is something like:
@Suppress("UNCHECKED_CAST")
fun <T> getProp(key: String): T {
val props = javaClass.classLoader.getResourceAsStream("pairs_ids.txt").use {
Properties().apply { load(it) }
}
return (props.getProperty(key) as T) ?: throw RuntimeException("could not find property $key")
}
it will read the properties and tries to cast a certain property. because of kotlins type inference it can then be used like this:
val foo: String = getProp("ETH_BTC")
or this:
val foo = getProp<String>("ETH_BTC")
val props = Properties()
props.load(...)
props.getProperty("key")
That is the same as with Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With