How to read properties file in resources folder of buildSrc module?

Viewed 1463

I need to read properties file located inside resources folder of buildSrc special module to create kotlin object which will be accessible by other project modules. I tried to put this properties file

  1. in the root project folder(this case sometimes works sometimes not, so I look for more reliable case)
  2. inside of buildSrc folder directly
  3. and now trying by putting inside "conventional" resources folder inside buildSrc which even highlighted by ide as recognized resources folder

But during assembling of modules I get Exception file not found on the line load()

So 2 questions:

  1. where properties file should be located
  2. how to read it from kotlin inside buildSrc module.

project structure dependencies.kt

2 Answers

Gradle has a somewhat complex class-loading hierarchy, and I don't know enough of it to be able to explain what is going on under the hood. However, I can give you some hints.

First of all, the methods getResource and getResourceAsStream is present in both a Class and a ClassLoader, and they behave differently.

On a Class, if you don't prefix it with a slash, it will look for resources relative to the package of the class. With a slash, it looks at the root of the hierarchy. As you don't know the package of the compiled script as done by Gradle, the correct way to reference the file is javaClass.getResourceAsStream("/file.properties") (notice the slash).

If you use the methods from a ClassLoader instead, a leading slash is meaningless. So here, Thread.currentThread().contextClassLoader.getResource("file.properties")) is correct.

The last thing to consider is when you can use the methods from the class and when you have to use a ClassLoader. From what I can tell, you can use the class method when in the same project (or plugin). So this should work from within buildSrc. But if you want to get the resource outside buildSrc, I believe you need to go through the context classloader.

After trying different variants I have found 100% stable and working variant - instead of reading a properties file, parsing it and validating input - just use kotlin objects as ready to use configuration! With this approach the problem of a current folder and accessibility of resources is gone which is what I needed. Property in kt files

Related