Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getClass().getResourceAsStream() in maven project

Tags:

The pom.xml of my maven project looks as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   <modelVersion>4.0.0</modelVersion>   <groupId>groupId</groupId>   <artifactId>artifactId</artifactId>   <version>0.0.1-SNAPSHOT</version>    <build>    <sourceDirectory>src/main/java</sourceDirectory>    <resources>     <resource>      <directory>src/main/resources</directory>     </resource>    </resources>   </build> </project> 

In the src/main/resources directory I have a file called test. In the src/main/java directory I have a class that contains the following line:

System.out.println(this.getClass().getResourceAsStream("test")); 

When the line of code is run within Eclipse, I get as output

java.io.BufferedInputStream@1cd2e5f  

When I export the project as .jar and run it I get as output

 null 

Did I configure anything wrong?

like image 646
hansi Avatar asked Feb 05 '13 02:02

hansi


People also ask

What is getClassLoader () getResourceAsStream?

class. getClassLoader(). getResourceAsStream("abc. txt") and find that it searchs the resource in all jar file and zip file in class path. Thats correct when you work only with a single ClassLoader (most non-OSGi/ non-modular environments).

How to Read a file using getResourceAsStream In java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How does getResource work?

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource.


2 Answers

Under <build><resources> make sure to have the <include> as below This will explicitly tell maven to fetch these files and include it in the build.

   <build>      <resources>         <resource>             <directory>${basedir}/src/main/resources</directory>             <includes>                 <include>**/*</include>             </includes>         </resource>      </resources>      ...   </build> 
like image 110
Milind J Avatar answered Sep 21 '22 07:09

Milind J


I was facing this same problem.

When you are trying to get the resource like this:
getClass().getResourceAsStream("test")

You are trying to find the resource relative to that package.

To get the resource from the src/main/resources directory, you have to put a slash before the resource name.
getClass().getResourceAsStream("/test")

like image 28
Rito Avatar answered Sep 21 '22 07:09

Rito