`
234390216
  • 浏览: 10198406 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
博客专栏
A5ee55b9-a463-3d09-9c78-0c0cf33198cd
Oracle基础
浏览量:461115
Ad26f909-6440-35a9-b4e9-9aea825bd38e
springMVC介绍
浏览量:1772239
Ce363057-ae4d-3ee1-bb46-e7b51a722a4b
Mybatis简介
浏览量:1395874
Bdeb91ad-cf8a-3fe9-942a-3710073b4000
Spring整合JMS
浏览量:394039
5cbbde67-7cd5-313c-95c2-4185389601e7
Ehcache简介
浏览量:678408
Cc1c0708-ccc2-3d20-ba47-d40e04440682
Cas简介
浏览量:529446
51592fc3-854c-34f4-9eff-cb82d993ab3a
Spring Securi...
浏览量:1179046
23e1c30e-ef8c-3702-aa3c-e83277ffca91
Spring基础知识
浏览量:462767
4af1c81c-eb9d-365f-b759-07685a32156e
Spring Aop介绍
浏览量:150327
2f926891-9e7a-3ce2-a074-3acb2aaf2584
JAXB简介
浏览量:66991
社区版块
存档分类
最新评论

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

    博客分类:
  • java
Web 
阅读更多

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

读文件很简单:

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();
		}
	}

 

2
8
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics