简体   繁体   中英

Not able to load properties file from classpath

I have an eclipse scala project which I am assembling with sbt. I want to add a properties file which I have tried placing in both the src and the target/scala/classes folders. I am not sure how to load this file in my program. This is my code:

val reader=this.getClass().getClassLoader().getResourceAsStream("ccm.properties") //Reading the properties file
val p=new Properties();  
p.load(reader);  
val maxDimension = p.getProperty("maxDimension").toInt 

This is the exception I am getting:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.musigma.ind.invictus.ConvergentCrossMapping.main(ConvergentCrossMapping.scala)
Caused by: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.musigma.ind.invictus.ConvergentCrossMapping$.<init>(ConvergentCrossMapping.scala:35)
    at com.musigma.ind.invictus.ConvergentCrossMapping$.<clinit>(ConvergentCrossMapping.scala)
    ... 1 more

UPDATE: This question is not a duplicate of this as I am writing this code in a Scala object and I cannot use this.class.getResourceAsStream(...)

Instead of java properties class, you can do it with ConfigFactory . File must be located under resources directory.

var b = getClass.getResource("/test.properties").getPath
val externalConfig1 = ConfigFactory.parseFile(new File(b))

println(externalConfig1.getInt("maxDimension"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM