Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resource from src/main/resources not found after building with maven

Hello I'm using a configuration file from src/main/resources in my java application. I'm reading it in my Class like this :

new BufferedReader(new FileReader(new File("src/main/resources/config.txt"))); 

So now I'm building this with maven using mvn assembly:assembly. Here is the bit for that in my pom.xml :

<plugin>                 <artifactId>maven-assembly-plugin</artifactId>                 <version>2.3</version>                 <configuration>                     <finalName>TestSuite</finalName>                     <descriptorRefs>                         <descriptorRef>jar-with-dependencies</descriptorRef>                     </descriptorRefs>                     <archive>                         <manifest>                             <addClasspath>true</addClasspath>                             <mainClass>com.some.package.Test</mainClass>                         </manifest>                     </archive>                 </configuration>             </plugin> 

So when I run my app I get this error :

src\main\resources\config.txt (The system cannot find the path specified) 

But when I right click on my assembled jar I can see it inside, anyone knows what I'm doing wrong?

like image 398
Gandalf StormCrow Avatar asked Apr 16 '12 08:04

Gandalf StormCrow


People also ask

Where is resources folder in Maven project?

By default, Maven will look for your project's resources under src/main/resources .


2 Answers

Resources from src/main/resources will be put onto the root of the classpath, so you'll need to get the resource as:

new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/config.txt"))); 

You can verify by looking at the JAR/WAR file produced by maven as you'll find config.txt in the root of your archive.

like image 78
beny23 Avatar answered Oct 17 '22 06:10

beny23


FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building. InputStream is = MyClass.class.getClassloader()                      .getResourceAsStream("config.txt"); 

Or you could extract the file from the jar before reading it.

like image 40
Peter Lawrey Avatar answered Oct 17 '22 08:10

Peter Lawrey