当Java
项目被打为可执行的jar
包后,执行jar
包时,如果读取相关的资源文件失败,可以按以下示例对源代码进行修改(既可以在IDE
中运行项目时正确读取,也可以在执行jar
包时正确读取):
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()
,在调用getResourceAsStream
或getResource
时,传入的参数就不能以/
开始;反之,必须以/
开始。
关于读取失败,可能是以下写法引起的(虽然在IDE
中运行项目时,这些写法是可以读取到资源文件的):
{
/**
* 打成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);
}
本作品由Daniate采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。