关于Properties类的使用

关于Properties类的使用

java.util.Properties ,是java获取配置信息的类
Properties类的关系图
Map<k,v>的map实现了Hashtable,使用map来保存配置信息,key值不能重复

构造方法

public Properties() {
        this(null);
    }

    /**
     * Creates an empty property list with the specified defaults.
     *
     * @param   defaults   the defaults.
     */
    public Properties(Properties defaults) {
        this.defaults = defaults;
    }

使用方法
1.一般我们可以获取java程序配置的jvm参数
方式1

Properties properties=System.getProperties();
properties.list(System.out);
//单个
properties.getProperty("cwNacosUserName");

方式2 获取某个jvm参数

 String jvmNacosUerName = System.getProperty("cwNacosUserName");

2 获取配置文件中的配置getClassLoader 加载

public class GetVersion {
    private static final Properties gitProperties;

    static {
        Properties prop = new Properties();
        try {
            ClassLoader classLoader = GetVersion.class.getClassLoader();
            InputStream in = classLoader.getResourceAsStream("gi t.comm.properties");
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        gitProperties = prop;
    }

    public static void main(String[] args) {
        System.out.println("commit id : " + gitProperties.getProperty("git.commit.id.abbrev"));
        System.out.println("commit time : " + gitProperties.getProperty("git.commit.time"));
    }

3.写入到Properties 文件

@Test
	public void writeTest(){
		try{
			Properties properties=new Properties();
			//用绝对路径
			InputStream input=new BufferedInputStream(new FileInputStream("D:\\workspace\\JavaLearn\\src\\jdbc.properties"));
			properties.load(new InputStreamReader(input,"utf-8"));
				//多添加值。
			properties.setProperty("id","1111");
			OutputStream output=new FileOutputStream("D:\\jdbc.properties");
			OutputStreamWriter out=new OutputStreamWriter(output,"utf-8");
			properties.store(out,"填充数据");
		}catch(Exception e){
			e.printStackTrace();
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值