properties read write example

public class PropertyUtil01 {

	private static Properties props = null;

	public static void main(String[] args) {
		PropertyUtil01 p;
		try {
			p = new PropertyUtil01();
			props = readProperties();
			System.out.println(readValue("name"));
			System.out.println(readValue("pwd"));
			setValue("url", "jdbc:db:xxx");
			System.out.println();
			System.out.println(p.readAllProperties());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Map<String, String> readAllProperties()
			throws FileNotFoundException, IOException {
		// 保存所有的键值
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<?> en = props.propertyNames();
		while (en.hasMoreElements()) {
			String key = (String) en.nextElement();
			String Property = props.getProperty(key);
			map.put(key, Property);
		}

		Iterator<Entry<String, String>> mapEntryItr = map.entrySet().iterator();
		while (mapEntryItr.hasNext()) {
			Map.Entry<String, String> maEntry = mapEntryItr.next();
			System.out.println(maEntry.getValue());
		}
		return map;
	}

	public static String readValue(String key) throws IOException {
		return props.getProperty(key);
	}

	public static void setValue(String key, String value) throws IOException {
		OutputStream fos = null;
		try {
			// e.g. D:\workspace\j2seTest1\bin\properties\config.properties
			fos = new FileOutputStream(PropertyUtil01.class.getClassLoader()
					.getResource("properties/").toURI().getPath()
					+ "config.properties");
			props.setProperty(key, value);
			props.store(fos, "comments: last update");
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} finally {
			fos.close();
		}
	}

	public static Properties readProperties() throws IOException {
		Properties prop = new Properties();
		InputStream fis = null;
		try {
			// e.g. D:\workspace\j2seTest1\bin\properties\config.properties
			fis = new FileInputStream(PropertyUtil01.class.getClassLoader()
					.getResource("properties/").toURI().getPath()
					+ "config.properties");
			prop.load(fis);
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} finally {
			fis.close();
		}
		return prop;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值