Search code examples
javamavenclassloader

Java getClassLoader().getResourceAsStream(filename)


I have a Maven project. My entire code is in the folder {PROJECT_ROOT}/src/main/java. When I write the code:

InputStream input = VertxApp.class.getClassLoader().getResourceAsStream("file.txt");
String result = getStringFromInputStream(input);
System.out.println(result);

I see that the code looks for the file named "file.txt" in the folder: {PROJECT_ROOT}/src/main/resources.

My question is why. Why doesn't it look for files in {PROJECT_ROOT}/src/main/java or in ${PROJECT_ROOT} for example?


Solution

  • Most Maven projects follow the structure of

    src/
      main/
        java/
        resources/
    

    You're intended to keep your non-code resources separate from your code. The getResourceAsStream method assumes this standard is followed, so it looks for your resource starting from the resources/ directory.

    See Why are project layout resources are kept separate from Java sources? for some more detailed thoughts.