java如何读取jar包下的配置文件

41次阅读
没有评论

共计 951 个字符,预计需要花费 3 分钟才能阅读完成。

可以使用 Java 中的 ClassLoader 来读取 jar 包下的配置文件。
使用 ClassLoader 的 getResourceAsStream 方法来读取 jar 包下的配置文件,代码示例如下:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFromJar {public static void main(String[] args) {
// 使用 ClassLoader 加载配置文件
InputStream inputStream = ReadConfigFromJar.class.getClassLoader().getResourceAsStream("config.properties");
Properties properties = new Properties();
try {
// 加载配置文件
properties.load(inputStream);
// 获取配置项的值
String value = properties.getProperty("key");
System.out.println(value);
} catch (IOException e) {e.printStackTrace();
} finally {if (inputStream != null) {
try {inputStream.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
}
}

在上述示例代码中,通过 ClassLoader.getResourceAsStream("config.properties") 方法来获取配置文件的输入流,然后使用 Properties 类加载输入流并获取配置项的值。需要注意的是,配置文件必须位于 classpath 下。
另外,需要将配置文件的路径以正确的相对路径方式传递给 getResourceAsStream 方法。如果配置文件位于 jar 包的根目录下,则直接使用文件名即可,如果配置文件位于 jar 包的子目录下,则需要将目录路径和文件名一起传递,例如"config/sub_config.properties"

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计951字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)