Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify path to resources inside a war file?

I have build my project with maven and spring framework using text editors. I am able to run the project the root folder using the command on terminal

mvn spring-boot:run

I have referenced to my source files inside java file using the java statement

Document doc = builder.parse("src/main/resources/data/resorts.xml");

Everything works fine.

When I export the whole project as a war file using the command

mvn package

on terminal

I get a war file inside the target folder of the root directory

I run the war file using the command

java -jar filename.war

There is no compilation error but during runtime it shows the error java.io.FileNotFoundException

I think I have not specified the path of the reference file correctly

Can you mention how the relative path must be mentioned in the the path string to make it able to be run from the war file.

My directory structure is

.
    |-- src
    |   `-- main
    |       |-- java
    |       |   `-- hello
    |       |       `-- org
    |       |           `-- json
    |       `-- resources
    |           |-- data
    |           `-- templates
    `-- target
        |-- classes
        |   |-- data
        |   |-- hello
        |   |-- org
        |   |   `-- json
        |   `-- templates
        |-- generated-sources
        |   `-- annotations
        |-- gs-handling-form-submission-0.1.0
        |   |-- META-INF
        |   `-- WEB-INF
        |       |-- classes
        |       |   |-- data
        |       |   |-- hello
        |       |   |-- org
        |       |   |   `-- json
        |       |   `-- templates
        |       `-- lib
        |-- maven-archiver
        `-- maven-status
            `-- maven-compiler-plugin
                `-- compile
                    `-- default-compile

    33 directories

The java files are inside the hello directory.

like image 305
Tejesh Raut Avatar asked Dec 04 '15 07:12

Tejesh Raut


1 Answers

You are probably experiencing problems with the path received from the URI class to a file located inside a jar.

Application.class.getClassLoader().getResource("path-to/filename.txt").getPath()

Outputs: /path-to-your/application.jar!/path-to/filename.txt

If you try to create a File object or a Stream to that path it will fail with FileNotFoundException

If possible you should change the class Document to receive the content of the file or a InputStream. Then you can use the classloader to fetch the stream for the file instead of the path.

In your case:

InputStream is = Application.class.getClassLoader()
            .getResourceAsStream("data/resorts.xml");

And then create the Document with the is object.

like image 80
stalet Avatar answered Nov 06 '22 12:11

stalet