Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read property file under classpath using scala

I am trying to read a property file from classpath using scala. But it looks like it won't work, it is different from java. The following 2 code snippet, one is java (working), another is scala (not working). I don't understand what is the difference.

// working
BufferedReader reader = new BufferedReader(new InputStreamReader(
Test.class.getResourceAsStream("conf/fp.properties")));

// not working 
val reader = new BufferedReader(new InputStreamReader(
getClass.getResourceAsStream("conf/fp.properties")));

Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at com.ebay.searchscience.searchmetrics.fp.conf.FPConf$.main(FPConf.scala:31)
at com.ebay.searchscience.searchmetrics.fp.conf.FPConf.main(FPConf.scala)
like image 231
zjffdu Avatar asked Feb 27 '13 10:02

zjffdu


3 Answers

This code finally worked for me:

import java.util.Properties
import scala.io.Source

// ... somewhere inside module.

var properties : Properties = null

val url = getClass.getResource("/my.properties")
if (url != null) {
    val source = Source.fromURL(url)

    properties = new Properties()
    properties.load(source.bufferedReader())
}

And now you have plain old java.util.Properties to handle what my legacy code actually needed to receive.

like image 187
Roman Nikitchenko Avatar answered Nov 16 '22 22:11

Roman Nikitchenko


I am guessing that your BufferedReader is a java.io.BufferedReader

In that case you could simply do the following:

import scala.io.Source.fromUrl
val reader = fromURL(getClass.getResource("conf/fp.properties")).bufferedReader()

However, this leaves the question open as to what you are planning to do with the reader afterwards. scala.io.Source already has some useful methods that might make lots of your code superfluous .. see ScalaDoc

like image 23
suls Avatar answered Nov 16 '22 21:11

suls


My prefered solution is with com.typesafe.scala-logging. I did put an application.conf file in main\resources folder, with content like:

services { mongo-db { retrieve = """http://xxxxxxxxxxxx""", base = """http://xxxxxx""" } }

and the to use it in a class, first load the config factory from typesafe and then just use it.

val conf = com.typesafe.config.ConfigFactory.load() conf.getString("services.mongo-db.base"))

Hope it helps!

Ps. I bet that every file on resources with .conf as extension will be read.

like image 3
Francisco López-Sancho Avatar answered Nov 16 '22 22:11

Francisco López-Sancho