Scala jar read external properties file

末鹿安然 提交于 2021-01-26 23:50:53

问题


I have written some code and exported it as a jar file. In this jar there is a file named automation.properties with defaults that I'm loading using

val automationPropertiesFileURL = getClass.getResource("/automation.properties")  
  if (automationPropertiesFileURL != null) {
    val source = Source.fromURL(automationPropertiesFileURL)
    config = new Properties()
    config.load(source.bufferedReader())
  }

But when this jar file gets added as a gradle dependency in C:\User\abc\.gradle and I want to read automation.properties from my current project, how can I override the location and read the file from my project and not from the jar file itself?


回答1:


The class loader will load the file from the location it finds first.

In your case, the file exists in two places:

  • Inside the current project itself
  • Inside a jar dependency

Which file will be found by the class loader, depends on the ordering of the "current project" and the jar dependency on the classpath. That's what you need to review, that's the key to loading the right file.

Your current code is correct as it is, this is a matter of classpath configuration.




回答2:


I think

Source.fromInputStream(
  getClass.getClassLoader.getResourceAsStream("/automation.properties")
)

should work.


API Docs

Source#fromInputStream

Class#getClassLoader

ClassLoader#getResourceAsStream




回答3:


Java and so does SCALA, have different ways of reading properties file, in one of my answers I explain the difference between reading from properties file inside the Jar and properties file in a disk location.

See my answer HERE: Loading Properties from a JAR file (java 1.6)

This will work for JAVA and for SCALA too! (Note, for SCALA you could change basic sintax but same concept)

Hope it helps!



来源:https://stackoverflow.com/questions/38583510/scala-jar-read-external-properties-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!