使用Maven无法访问资源目录中的文件(使用Eclipse IDE)

我有几个小时的问题,我尝试了我在教程中找到的所有解决方案。 这很简单:我无法访问资源文件。 我尝试打开一个我放在src/main/resourcessrc/test/resources

我有一个简单的Java项目,我使用Maven,Eclipse作为IDE,使用m2e插件。 我想使用Maven的资源过滤,具有不同的配置文件,并且有我的POM.xml

    org.apache.maven.plugins maven-compiler-plugin 2.3.2  1.5 1.5 false true    org.apache.maven.plugins maven-resources-plugin 2.4  UTF-8     src/main/filters/${env}.properties    src/main/resources true   src/test/resources true      LOCAL  true   local    

我在src / java / test中做了一个简单的测试:

 @Test public void testOpenResourceFile() { File testf=new File("/test.txt"); assertTrue(testf.exists()); } 

所以,在Eclipse中,我运行(在我的项目文件夹中,在包视图中):

  • 运行方式> Maven build> process-resources
  • 运行方式> Maven build> process-test-ressources
  • 运行方式> Maven build> compile

使用env:LOCAL

在测试中,我做:运行为> Junit测试用例。 但它失败了…我查看了Maven生成的target / test-classes目录,并且文件test.txt就在那里。

在我的项目编译期间,我是否错过了一些步骤,或者我的配置是否有问题?

编辑:
我也试过File("test.txt")File("../test.txt")

它看起来像你的问题

 File testf = new File( "/test.txt" ); 

那是在你的计算机文件系统的根目录下寻找一个名为test.txt的文件。 你想要的是资源树的根,你可以用getResource方法得到它:

 File testf = new File( this.getClass().getResource( "/test.txt" ).toURI() ); 

或者,在静态上下文中,使用包含类的名称:

 File testf = new File( MyClass.class.getResource( "/test.txt" ).toURI() ); 

当然,您需要为该示例添加error handling。

我遇到了同样的问题,只需确保“text.txt”文件位于测试项目的资源文件夹(src / test / resources / text.txt)中,而不是任何其他资源文件夹中。 此外,您应该从资源文件夹中检索文件,如下所示:

 this.getClass().getClassLoader().getResource("text.txt").getFile(); 

如果这仍然不起作用,那么尝试在pom.xml中将maven-surefire-plugin useSystemClassLoader maven-surefire-pluginuseSystemClassLoader设置为false。

http://maven.apache.org/surefire/maven-surefire-plugin/examples/class-loading.html

检查pom.xml中的标签应该是这样的,遇到同样的问题,并在添加这个标签为我工作。

    true src/main/resources    

我为这项工作制作了这个方法:

 public static String getPropaccess(String key){ String value=""; Properties configFile = new Properties(); try { configFile.load(Propaccess.class.getClassLoader().getResourceAsStream("test/resources/config.properties")); value = configFile.getProperty(key); return value; } catch (IOException e) { e.printStackTrace(); } return value; }