在Java应用程序中,从jar文件中加载资源通常涉及到使用ClassLoader
的getResourceAsStream
方法。这个方法允许你从类路径中查找资源,并返回一个输入流,你可以使用这个输入流来读取资源内容。
ClassLoader
的一个方法,用于从类路径中查找资源并返回一个InputStream
。假设你有一个名为config.properties
的配置文件放在了src/main/resources
目录下,编译后这个文件会被打包到jar文件中。你可以这样加载它:
Properties prop = new Properties();
InputStream input = null;
try {
// 使用当前类的类加载器来加载资源
input = getClass().getClassLoader().getResourceAsStream("config.properties");
// 加载属性文件
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return;
}
prop.load(input);
// 读取属性
String propertyValue = prop.getProperty("propertyKey");
System.out.println(propertyValue);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过上述方法,你可以有效地从Java应用程序的jar文件中加载资源。
领取专属 10元无门槛券
手把手带您无忧上云