[英]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. 在File1.java中,我尝试获取read.txt的路径,该路径位于/ src / main / resources文件夹中。
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 ie http://<ip>:8080, /src/main/resources path is not accessible.
当我在Tomcat上( ie http://<ip>:8080, /src/main/resources path is not accessible.
部署此jar时, ie 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. 我创建了一个KnitProject应用程序jar并将其部署在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 . / src / main / resources /可从我的本地计算机访问,并且相同的代码给出错误FileNotFound Exception 。
How can I read the file which is under /src/main/resources/data. 如何读取/ 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. 我在代码中使用Embedded Jetty服务器,并且将其编译并构建为一个Jar,然后部署在Tomcat中。 I am running jar using JNLP. 我正在使用JNLP运行jar。
You can use resourceAsStream
method to read the file from jar 您可以使用resourceAsStream
方法从jar中读取文件
InputStream stream = Encrypter.class.getResourceAsStream(filePath)
Now with this stream you can proceed 现在,通过此流,您可以继续
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.