读Properties文件和往Properties文件里面写内容

读取配置文件是一个很常用的操作;

读文件很简单:

public static String getProperty(String key) {
		String value = "";
//第一步是取得一个Properties对象
		Properties props = new Properties();
//第二步是取得配置文件的输入流
		InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");//在非WEB环境下用这种方式比较方便
		try {
			InputStream input = new FileInputStream("config.properties");//在WEB环境下用这种方式比较方便,不过当配置文件是放在非Classpath目录下的时候也需要用这种方式
//第三步讲配置文件的输入流load到Properties对象中,这样在后面就可以直接取来用了
			props.load(input);
			value = props.getProperty(key);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}

 

往配置文件里面写内容:

public static void setProperty(Map<String,String> data) {
//第一步也是取得一个Properties对象
		Properties props = new Properties();
//第二步也是取得该配置文件的输入流
//		InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");
		try {
			InputStream input = new FileInputStream("config.properties");
//第三步是把配置文件的输入流load到Properties对象中,
			props.load(input);
//接下来就可以随便往配置文件里面添加内容了
//			props.setProperty(key, value);
			if (data != null) {
				Iterator<Entry<String,String>> iter = data.entrySet().iterator();
				while (iter.hasNext()) {
					Entry<String,String> entry = iter.next();
					props.setProperty(entry.getKey().toString(), entry.getValue().toString());
				}
			}
//在保存配置文件之前还需要取得该配置文件的输出流,切记,如果该项目是需要导出的且是一个非WEB项目,则该配置文件应当放在根目录下,否则会提示找不到配置文件
			OutputStream out = new FileOutputStream("config.properties");
//最后就是利用Properties对象保存配置文件的输出流到文件中;
			props.store(out, null);
			input.close();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值