【问题标题】:My java application does not read my files (maven project)我的 java 应用程序不读取我的文件(maven 项目)
【发布时间】:2015-07-17 17:47:06
【问题描述】:

我在一个 Java 简单项目中有一个应用程序。但是,我需要将此项目粘贴到 Maven 项目中。所以,我基本上做了一个简单的 Maven 项目,我把我所有的类复制粘贴到里面。我需要一个在服务器中运行的战争,我需要像 Java 应用程序一样运行 Main,因为这个应用程序配置了战争应用程序。但是,当我运行 Main 时,我遇到了一些以前没有的错误:

java.io.FileNotFoundException: resources\config.properties(系统找不到指定的路径)

当在代码中是:

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

这也不起作用:

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

我该如何解决这个问题?

【问题讨论】:

  • 尽量不要引用资源,而是尝试使用类似getClass().getResourceAsStream("/config.properties") 的东西。根据您的 Maven 设置,这些文件可能已包含在生成的 Jar 文件中。您可能想打开(使用任何 zip 程序)并检查。根据我(有限的理解),resources 包含在类路径中

标签: java eclipse file maven


【解决方案1】:

在一个简单的 Mavne 项目中,所有资源都应该位于 src/main/resources 中。然后可以通过(对于非静态方法)获取属性文件:

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

对于静态方法,请使用: <Class name>.class.getClassLoader().getResourceAsStream("config.properties");

请参阅此链接了解更多信息: Reading properties file

【讨论】:

    【解决方案2】:

    如果您使用的是“简单的 maven 项目”,那么 maven 方式是要有一个 src/main/resources 文件夹。你有没有配置你的 pom.xml 来做一些不同的事情?

    如果您已正确完成 jar 创建部分,则获取类路径上的文件的正确方法是:

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

    前导斜杠很重要!

    如果文件不在您的类路径中(换句话说,如果上述方法不起作用,就会出现这种情况),您可能需要配置 maven 以使用不同的资源目录。

    你这样做like this(根据需要更改参数):

    <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>
    

    然后,您的文件将位于您的类路径中,并且上述代码将起作用。阅读上面的链接文档了解更多信息。

    【讨论】:

    • 非常感谢,这有助于我使用属性。我意识到我的错误是另一回事。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2012-10-11
    • 2016-08-03
    • 2012-03-09
    • 2017-05-24
    相关资源
    最近更新 更多