读取jar包内的资源文件

Java项目被打为可执行的jar包后,执行jar包时,如果读取相关的资源文件失败,可以按以下示例对源代码进行修改(既可以在IDE中运行项目时正确读取,也可以在执行jar包时正确读取):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Properties prop = new Properties();
String resourceName = "com/daniate/resource/configInPkg.properties";
//String resourceName = "configOutsidePkg.properties";
{
// 最前面无斜杠
InputStream input = this.getClass().getClassLoader().getResourceAsStream(resourceName);
prop.load(input);
}
{
// 最前面无斜杠
InputStream input = this.getClass().getClassLoader().getResource(resourceName).openStream();
prop.load(input);
}
{
// 最前面有斜杠
InputStream input = this.getClass().getResourceAsStream("/" + resourceName);
prop.load(input);
}
{
// 最前面有斜杠
InputStream input = this.getClass().getResource("/" + resourceName).openStream();
prop.load(input);
}

上面的四种写法任选其一。

如果使用了getClassLoader(),在调用getResourceAsStreamgetResource时,传入的参数就不能以/开始;反之,必须以/开始。

关于读取失败,可能是以下写法引起的(虽然在IDE中运行项目时,这些写法是可以读取到资源文件的):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
/**
* 打成jar包后运行: Caused by:
* java.io.FileNotFoundException:
* file:\E:\workspace-netbeans\XX\dist\XX.jar!\configOutsidePkg.properties
* (文件名、目录名或卷标语法不正确。)
*/
URL url = this.getClass().getResource("/" + resourceName);
Reader reader = new FileReader(url.getPath());
prop.load(reader);
}
{
/**
* 打成jar包后运行: Caused by:
* java.lang.IllegalArgumentException: URI is not hierarchical
*/
URL url = this.getClass().getResource("/" + resourceName);
Reader reader = new FileReader(new File(url.toURI()));
prop.load(reader);
}
{
/**
* 打成jar包后运行:Caused by:
* java.io.FileNotFoundException: src\config.properties
* (系统找不到指定的路径。)
*/
Reader reader = new FileReader(new File("src/" + resourceName));
prop.load(reader);
}

读取jar包内的资源文件
https://daniate.github.io/2017/03/18/读取jar包内的资源文件/
作者
Daniate
发布于
2017年3月18日
许可协议