Search code examples
javajava-web-startembedded-resourcejnlp

Reading file from /src/main/resources gives exception FileNotFound


My project has the following structure:

KnitProject - Project Name
/src/main/java/com/knit/controller/File1.java
/src/main/resources/data/read.txt

In File1.java, I am trying to get the path of read.txt which is inside /src/main/resources folder.

Main.java
=========
Server server = new Server(8585);
.....
.....
server.start();
server.join();

File1.java
==========
URL url = Encrypter.class.getResource("/data/read.txt");
System.out.println(url.getFile()); //This prints "C:/Users/KnitProject/target/classes/data/read.txt" which is working locally from my system

When I deploy this jar in Tomcat i.e http://<ip>:8080, /src/main/resources path is not accessible.

System.out.println(url.getFile()); //This prints "http://<ip>:8080/test/target/KnitProject.jar!/data/read.txt.

when trying to read file using

FileInputStream fileInputStream = new FileInputStream(new File(url.getFile())) ---> gives me error FileNotFound Exception when deployed in Tomcat

I have created jar of KnitProject application and deployed it in Tomcat. Can anyone help me what I am doing wrong. /src/main/resources/ is accessible from my local machine and same code is giving error FileNotFound Exception.

How can I read the file which is under /src/main/resources/data. I am using Embedded Jetty server in my code and same is compilled and build as one Jar and then deployed in Tomcat. I am running jar using JNLP.


Solution

  • You can use resourceAsStream method to read the file from jar

    InputStream stream = Encrypter.class.getResourceAsStream(filePath)
    

    Now with this stream you can proceed