Java .properties file not found in directory

95 views Asked by At

I am pretty new developer in Java and so I am a little bit confused with the .properties file. I know how JVM looks for them during the runtime but I have a slightly different problem.

I have a resources directory in my project folder in which there is a strings sub-directory where I store all string values in all languages, kinda like in Android Studio when you create an empty project.

I want to have access to the .properties files contained in the strings directory from all packages I have in my project.

  • resources
    • strings
      • strings_en.properties
      • strings_it.properties
  • myfirstpackage
    • src
      • com
        • example
          • File.java
  • mysecondpackage
    • src
      • com
        • example
          • AnotherFile.java
  • src
    • com
      • example
        • Main.java

Every time I try to call ResourceBundle.getBundle() and specify name and locale I get an exception which tells me that my bundle does not exist.

  1. I have already tried to specify relative path from the file I am requesting the .properties values;
  2. I have already tried to specify relative path from the project root folder to get .properties file loaded up;
  3. I tried renaming the file from strings_en.properties to strings_en.java and the same thing for the Italian one.

I hope someone can explain how I can implement this this and how to work with the properties file later in the future.

Thanks in advance.

1

There are 1 answers

1
JDev On BEST ANSWER

You're on the right path! When compiled, the files in the resources folder are moved to the root directory. They are not moved out of any parent folders though, so you still have to give a relative path from any folders that are direct children of the resources folder.

I found a little snip from a mkyong post that explains this a bit more clearly:

By default, build tools like Maven, Gradle, or common Java practice will copy all files from src/main/resources to the root of target/classes or build/classes. So when we try to read a file from src/main/resources, we read the file from the root of the project classpath.

So here is your structure:

resources
    strings
        strings_en.properties
        strings_it.properties

With that, calling ResourceBundle.getBundle("strings/strings", Locale.English) should return the strings_en.properties values.

enter image description here

# strings/strings_en.properties
hello=hello
public static void readProperties() {
    ResourceBundle bun = ResourceBundle.getBundle("strings/strings", Locale.ENGLISH);
    System.out.println(bun.getString("hello"));
}
    
prints: hello