我有结构的Java项目如下:我怎样才能得到资源文件夹中的输出结果?
我可以使用代码读取hotels.csv
文件;
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("hotels.csv").getFile());
我有也需要在同一文件夹中所示的图像中results.xml
输出文件。目前,我这样做,使用的代码,
StreamResult result = new StreamResult(new File("src/main/resources/result.xml"));
我如何能做到这一点通过编程只说文件名,比方说,result.xml
并获得使用该程序的路径?
我在论坛上看到过一篇关于同一个问题的帖子,在下面的帖子后没有得到任何结果。我配置了pom.xml
文件,如下图所示
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>Trivago</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>${RESOURCE_PATH}</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<packaging>jar</packaging>
<name>Trivago</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Use the latest version whenever possible. -->
<jackson.version>2.4.4</jackson.version>
<RESOURCE_PATH>${project.basedir}/src/main/resources</RESOURCE_PATH>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-resources-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
</project>
一个后来尝试使用方法获取的资源文件夹的路径的建议,
private static String getResourcePath() {
try {
URI resourcePathFile = System.class.getResource("/RESOURCE_PATH").toURI();
String resourcePath = Files.readAllLines(Paths.get(resourcePathFile)).get(0);
// System.out.println("resourcePath = " + resourcePath);
URI rootURI = new File("").toURI();
URI resourceURI = new File(resourcePath).toURI();
URI relativeResourceURI = rootURI.relativize(resourceURI);
return relativeResourceURI.getPath();
} catch (Exception e) {
return null;
}
}
福斯产品,我打算用 StreamResult result = new StreamResult(new File(getResourcePath() +"/result.xml"));
我得到java.lang.NullPointerException
运行这条命令时URI resourcePathFile = System.class.getResource("/RESOURCE_PATH").toURI();
更新:我也运行命令mvn generate-resources process-resources
在post