我有一个简单的应用程序,可以从资源目录中读取一个文本文件。我的应用程序结构:-
我的 pom.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
<artifactId>ReadFileExample</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ReadFileExample</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.txt</include>
</includes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>org.example.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
我的简单代码:-
public class App {
public static void main( String[] args ) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(Objects.requireNonNull(
Objects.requireNonNull(App.class.getClassLoader().getResource("file.txt")).getFile())));
String line = "";
while ( (line = bufferedReader.readLine()) != null ){
System.out.println(line);
}
}
}
此代码在 IDE 运行时有效。但我想通过带有资源文件的可执行 jar 来运行它。当我以 java -jar ReadFileExample-1.0-SNAPSHOT.jar
运行时,出现以下错误:-
线程“main”中的异常java.io.FileNotFoundException: 文件:/home/dev/dev/ReadFileExample/target/ReadFileExample-1.0-SNAPSHOT.jar!/file.txt (没有这样的文件或目录)在 java.io.FileInputStream.open0(Native 方法)在 java.io.FileInputStream.open(FileInputStream.java:195) 在 java.io.FileInputStream.(FileInputStream.java:138) 在 java.io.FileInputStream.(FileInputStream.java:93) 在 java.io.FileReader.(FileReader.java:58) 在 org.example.App.main(App.java:15)
当我通过 vi 访问 jar 时,我可以看到以下内容:-
我很困惑,资源文件在 resource/file.txt 中,但它被带到了根目录。我不知道它的结构是否正确。
如何在这个jar中添加资源文件?