My folder structure inside src is like so:
src
├── main
│ ├── java
│ │ └── com
│ │ └── organization
│ │ └── projectname
│ │ ├── Transformer.java
│ │ └── Utils.java
│ └── resources
│ └── config
└── test
├── java
│ └── com
│ └── organization
│ └── projectname
│ └── AppTest.java
└── resources
└── file
└── test.txt
and I want to read the test.txt file.
I do use Maven & Eclipse, but I'd like the same code to run when I package in JAR (with mvn package) and when someone is running inside IDE or by commandline.
My attempt here fails (gets null):
InputStream input = Scorer.class.getResourceAsStream("file/test.txt");
System.out.println(input); // prints null
as does this attempt (gets null):
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("file/test.txt");
System.out.println(url.getFile()); // prints null
I'm quite confident the file does exist at that location inside src/test/resources/file/, so I'm wondering what else I am doing wrong.
Thanks!
Given that test.txt is in src/test/resource it will not be available in the jar file nor when you run the app in your IDE, unless if you're running test units. Here is an Introduction to the Standard Directory Layout
I suggest to move it in src/main/resource.
Moving into src/main/resource will make able your IDE to have the resource available when you run or debug your project.
On the other hand, Maven will be able to copy the resources into the jar when you run the mvn package goal.
To be sure that mvn package goal copy the files into the Jar just add these lines into your pom project:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**.txt</include>
</includes>
</resource>
</resources>
</build>
Have a look at Maven Resource Plugin to understand how to write the <resource> configuration.
And pay attention to this: if you update your maven pom.xml file, adding one or more <resource> part this does not mean that conversely your IDE update the project with this behaviour/configuration (i.e. copy the resources).
So each time you have to check both Maven pom.xml and the IDE project configuration.