Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put static file in Maven project

Tags:

java

file

maven

I have created a simple Maven project with no archetype, everything is okay. Then I added a CVA.pmml file under the main/resources directory. Afterwards, I want to read the file but get FileNotFoundException. I tried the following methods:

Method 1:

InputStream is = BundleTest.class.getResourceAsStream("CVA.pmml");

Method 2:

InputStream is = BundleTest.class.getResourceAsStream("resources/CVA.pmml");

Method 3:

InputStream is = new FileInputStream("CVA.pmml");

Method 4:

InputStream is = new FileInputStream("resources/CVA.pmml");

None of them works. Any suggestion?

Here is the screenshot of the project structure:

Project Structure

like image 743
Yi Luo Avatar asked Oct 17 '25 01:10

Yi Luo


1 Answers

Method 1:

InputStream is = BundleTest.class.getResourceAsStream("CVA.pmml");

That will look for the CVA.pmml resource in the same package as the BundleTest class. But CVA.pmml is in the root package, whereas BundleTest is not.

Method 2:

InputStream is = BundleTest.class.getResourceAsStream("resources/CVA.pmml");

That will look for it in the resources package under the package of the BundleTest class. But it's in the root package.

Method 3:

InputStream is = new FileInputStream("CVA.pmml");

That wil look it on the file system, in the directory from which you executed the java command. But it's in the classpath, embedded in the jar (or in a classpath directory)

Method 4:

InputStream is = new FileInputStream("resources/CVA.pmml");

That wil look it on the file system, in the directory `resources, under the directory from which you executed the java command. But it's in the classpath, embedded in the jar (or in a classpath directory)

The correct way is

InputStream is = BundleTest.class.getResourceAsStream("/CVA.pmml");

(notice the leading slash)

or

InputStream is = BundleTest.class.getClassLoader().getResourceAsStream("CVA.pmml");
like image 156
JB Nizet Avatar answered Oct 18 '25 18:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!