java项目加载配置文件的工具类

本文介绍了一个用于Java项目的配置文件加载工具类,该工具采用单例模式实现,并提供了加载配置文件、获取配置值及设置配置的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java项目加载配置文件的工具类

package com.loadproperties;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigUtil {

	private static InputStream input;
	
	private volatile Properties configuration = new Properties();
	
	//弄成单例的
	private static ConfigUtil config;
	public static ConfigUtil getInstance(String path){
		if(config==null)
		{
			config=new ConfigUtil(path);
		}
		return config;
	}
	
	//构造函数内完成了加载配置文件
	private ConfigUtil(String path)
	{
		input =this.getClass().getResourceAsStream(path);
		this.configuration.clear();
        try {
			this.configuration.load(input);
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	public String getStringValue(String key) throws IOException
    {
        return this.configuration.getProperty(key);
    }
	
	public String getStringValue(String key, String defaultValue) 
	{
		String value = this.configuration.getProperty(key);
		if (value == null) {
			return defaultValue;
		} else {
			return value;
		}
	}
	
	 public void setConfiguration(String key, String value)
	 {
	    this.configuration.setProperty(key, value);
	 }
	 
	public static void main(String[] args) throws IOException {
		String path="/com/loadproperties/log4j.properties";
		System.out.println(config.getInstance(path).getStringValue("log4j.rootLogger"));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值