Search code examples
javaiojava-11

How best to access a file from resources folder


In a java project I need to access a file from the resources folder. I am able to do so in the following 3 ways:

// 1
new File("src/main/resources/a.txt")
// 2
new URL("file:src/main/resources/a.txt")
// 3
getClass().getClassLoader().getResource("a.txt")

All these approaches seem to work. Is any of these approaches preferential?


Solution

  • The third one is the only one that will work once your program will be packaged (Jar or War).