import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
// 创建Properties对象,用于读取配置文件
Properties properties = new Properties();
try {
// 获取类加载器并读取jar包中的配置文件
InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream("config.properties");
if (inputStream != null) {
// 加载输入流中的属性到Properties对象
properties.load(inputStream);
// 关闭输入流
inputStream.close();
// 读取配置项
String value = properties.getProperty("key");
System.out.println("Value: " + value);
} else {
System.out.println("配置文件未找到");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
ConfigReader.class.getClassLoader().getResourceAsStream("config.properties")获取类加载器,并读取位于jar包根目录下的config.properties文件。如果配置文件在某个子目录中(例如resources/config.properties),则路径应为"resources/config.properties"。properties.load(inputStream)将输入流中的内容加载到Properties对象中。properties.getProperty("key")获取配置文件中指定键对应的值。确保你的配置文件(如config.properties)放置在项目的资源目录中,打包成jar后也会包含在其中。
上一篇:java定义类
下一篇:java读取excel文件内容
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站