Properties类

前言:

         在部署程序时总会有些变量需要随着环境的变化或者其它原因,需要进行修改。如果这些参数是直接写死在程序中,那么我们每次修改都需要重新编译,不是很方便。

      有两种解决方法: 1、使用spring注入的方式,将参数值传入;2:、写入文件中进行解析。

 对于方法1,如果多个bean需要传参,逐一查找不方便,可以使用占位符,将参数和对应值统一写到一个文件中,编译的时候进行替换,最终的内部机制和方法2一样。

      使用Properties类可以对配置文件进行解析,将其以key/value对的形式,进行set 和get。

一:Properties类介绍

      Properties类是Hashtable<Object,Object>的子类,有getProperty()  load()  store()  setProperty()  clear()方法

其中: public String getProperty(String key)   传入一个key值返回对应的value值;

            load(InputStream inStream)   加载文本的输入流,解析里面以 xxx=yyy存储的信息

            public synchronized Object setProperty(String key, String value)  设置 k / v 对
            public void store(OutputStream out, String comments)  将hashtable存储的k/v对信息,输出到输出流,参数comments是自定义的注释信息

           clear() 清空hashtable

二: 简单实例

package com.netboy.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取配置文件search.properties的demo程序
 * 
 */
public class SimpleMain {
	public static void main(String[] args) throws IOException {
		String filePath = "./conf/search.properties";

		FileInputStream fileStream = new FileInputStream(filePath);
		FileOutputStream outputStream = new FileOutputStream("./conf/store.properties");
		Properties properties = new Properties();
		properties.load(fileStream);
		System.out.println("the daily.ip is :" + properties.getProperty("daily.ip"));
		System.out.println("the local.ip is :" + properties.getProperty("local.ip"));
		System.out.println("the online.ip is :" + properties.getProperty("online.ip"));
		System.out.println("the jetty.port is :" + properties.getProperty("jetty.port"));
		properties.setProperty("netboy", "search demo");
		properties.store(outputStream,"test");
		properties.clear();
		System.out.println("Hello World!");
	}
}

search.properties内容如下:

daily.ip=192.168.1.1
local.ip=127.0.0.1
online.ip=222.222.222.222
!jetty.port=8989
#jetty.port=8989

注意:由源码可以看出,使用! 和# 都可以起到注释的作用,properties.java 源码片段:

		if (isNewLine) {
		    isNewLine = false;
		    if (c == '#' || c == '!') {
			isCommentLine = true;
			continue;
		    }
		}

工程框架:



三:这里只是简单介绍下,使用占位符进行自动替换打包,可以参考我之前的文章:   简单 maven工程 spring注入 自动打包


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值