java怎么读取jar包下的配置文件

   2025-02-22 5190
核心提示:在Java中,可以使用以下代码读取JAR包中的配置文件:import java.io.InputStream;import java.util.Properties;public class Rea

在Java中,可以使用以下代码读取JAR包中的配置文件:

import java.io.InputStream;import java.util.Properties;public class ReadConfigFile {public static void main(String[] args) {try {// 读取JAR包中的配置文件InputStream inputStream = ReadConfigFile.class.getResourceAsStream("/config.properties");// 创建Properties对象Properties properties = new Properties();// 加载配置文件properties.load(inputStream);// 获取配置项的值String value = properties.getProperty("key");System.out.println("Value: " + value);// 关闭输入流inputStream.close();} catch (Exception e) {e.printStackTrace();}}}

上述代码中,ReadConfigFile类通过getResourceAsStream方法获取JAR包中的配置文件config.properties的输入流。然后使用Properties对象加载配置文件,并通过getProperty方法获取配置项的值。

请注意,要使用绝对路径来指定JAR包中的配置文件,即以/开头。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言