2015-04-01 149 views
0

所以,我有以下文件夹结构:如何将外部文件夹添加到类路径中?

  • 项目
    • LIB (运行此文件夹中的jar)
    • 属性(属性文件加载是此文件夹中)

我想通过X.class.getClassLoader()。getResource(“properties/fileName”)加载属性文件。此方法在eclipse中工作,但是当我使用maven构建jar时,它无法找到该文件,从而导致文件未找到异常。

我怀疑该文件夹不在类路径中,因为如果我运行getClassLoader()。getResources(“”)属性文件夹永远不会显示。我在以前的问题上尝试了所有关于stackoverflow的建议,但目前还没有任何建议。

我也试着运行java -cp和-classpath,但仍然失败。

回答

0

使用Maven时,默认情况下,文件如*.properties和任何其他不可编译的文件必须位于src/main/resources文件夹中。

此外,我建议您使用Thread.currentThread().getContextClassLoader()来获取正确的类加载器,以加载资源。

无论如何,如果你想拥有在类路径的自定义文件夹,我建议你添加为资源,在pom.xml,就像这样:

<project> 
    ... 
    <build> 
     ... 
     <resources> 
      <resource> 
       <!-- The folder you want to be a resource (from project root folder), like: project/properties --> 
       <directory>properties</directory> 
       <!-- Filtering if Maven should post-process text files to find and replace ${key} params: in most cases, leave it false --> 
       <filtering>false</filtering> 
      </resource> 
     </resources> 
    </build> 
</project> 
+0

当我尝试你的建议,getClassLoader()。 getResources(“”)找到一个URL,但是当它传递给FileInputStream构造函数时,我得到一个文件未找到的异常。我想我可以使用Thread.currentThread()。getContextClassLoader(),但我坚持遗留代码... – StickStack 2015-04-01 17:52:23

+0

我认为你的类加载器没有看到该文件。没有办法改变类加载器吗?它可以为你解决这个问题...无论如何,我会花一些时间并检查解决方法。 – 2015-04-01 20:36:20

+1

类加载器从来没有看到该文件,因为它不在类路径中,不管我做什么。我希望我能改变类加载器,但我不能。我在不再使用类加载器的地方做了一个工作,因此它现在已经“固定”了。感谢您的帮助,不需要浪费您的时间。 – StickStack 2015-04-01 20:49:11

相关问题