My java application does not read my files (maven project)

前提是你 提交于 2021-02-07 14:49:01

问题


I have an application in a Java simple project. However, I need to paste this project to a Maven project. So, I basically made a simple Maven project, and I copied and pasted all my classes into it. I need a war to run in a server, and I need to run a Main like a Java application, because this application configures the war application. However, when I run Main, I get some errors that I wasn't having before:

java.io.FileNotFoundException: resources\config.properties (The system cannot find the path specified)

when in the code is:

input = new FileInputStream("resources/config.properties");

This didn't work either:

faceDetector = new CascadeClassifierDetector("D:/retinoblastoma/workspace/Resources/CascadeClassifiers/FaceDetection/haarcascade_frontalface_alt.xml");

How can I fix this?


回答1:


If you're using a "simple maven project", the maven way is for there to be a src/main/resources folder. Did you configure your pom.xml to do something different than that?

If you've done the jar creation portion correctly, the right way to get a file that's on the classpath is:

getClass().getResourceAsStream("/path/to/resource.ext");

The leading forward slash is important!

If the file is NOT on your classpath (in other words, this will be the case if the above doesn't work), you probably need to configure maven to use a different resources directory.

You do that like this (change the arguments as appropriate):

<build>
  ...
  <resources>
    <resource>
      <targetPath>META-INF/plexus</targetPath>
      <filtering>false</filtering>
      <directory>${basedir}/src/main/plexus</directory>
      <includes>
        <include>configuration.xml</include>
      </includes>
      <excludes>
        <exclude>**/*.properties</exclude>
      </excludes>
    </resource>
  </resources>
  <testResources>
    ...
  </testResources>
  ...
</build>

Then, your file will be on your classpath and the above code will work. Read the linked documentation above for more information.




回答2:


In a simple Mavne project, all the resources should be located in src/main/resources.You can get the properties file then by (for a non-static method) :

Properties prop = new Properties(); prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));

For a static method, use : <Class name>.class.getClassLoader().getResourceAsStream("config.properties");

Refer this link for more information : Reading properties file



来源:https://stackoverflow.com/questions/31466993/my-java-application-does-not-read-my-files-maven-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!