Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can read content data from properties file to Properties object?

Tags:

kotlin

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)
like image 341
Alexei Avatar asked Jan 23 '19 21:01

Alexei


People also ask

How do you load the data from the properties file?

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.

How read data from properties file in selenium?

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.

How read data from properties file in Python?

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.


2 Answers

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")
like image 79
Christian Dräger Avatar answered Sep 21 '22 21:09

Christian Dräger


val props = Properties()
props.load(...)
props.getProperty("key")

That is the same as with Java

like image 39
Eugene Petrenko Avatar answered Sep 22 '22 21:09

Eugene Petrenko