gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:38:17 26 4
gpt4 key购买 nike

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

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

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
<debug>false</debug>
<optimize>true</optimize>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>

<filters>
<filter>src/main/filters/${env}.properties</filter>
</filters>

<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>

<profiles>
<profile>
<id>LOCAL</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<env>local</env>
</properties>
</profile>
</profiles>

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

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

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

  • 运行方式 > Maven 构建 > 流程资源
  • 运行方式 > Maven 构建 > process-test-ressources
  • 运行方式 > Maven 构建 > 编译

使用环境:本地

在测试中,我这样做: Run as > 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() );

当然,您需要在该示例中添加错误处理。

关于java - 无法使用 Maven 访问资源目录中的文件(使用 Eclipse IDE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19916845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com