首页 > 代码库 > Java之Property类使用
Java之Property类使用
http://blog.csdn.net/hopestar2/article/details/6372883
在项目中经常用到各种配置文件,有.properties的,也有.xml格式的
都可以通过java.utils.Property类进行处理。
1. 读取.properties文件
[c-sharp] view plain copy
- File pFile = new File("test.properties");
- FileInputStream pInStream=null;
- try {
- pInStream = new FileInputStream(pFile );
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- Properties p = new Properties();
- try {
- p.load(pInStream );
- } catch (IOException e) {
- e.printStackTrace();
- }
- Enumeration enu = p.propertyNames(); //取出所有的key
- p.list(System.out) ;
- while(enu.hasMoreElements())
- {
- String thisKey = (String)enu.nextElement();
- System.out.println("key="+thisKey);
- System.out.println("value="http://www.mamicode.com/+p.getProperty(thisKey));
- }
.properties测试文件内容如下:
name = tinyfun
age = 25
sex = man
title = software developer
2. 读取XML文件
[java] view plain copy
- File pFile = new File("test.xml");
- FileInputStream pInStream = null;
- try {
- pInStream = new FileInputStream(pFile);
- Properties p = new Properties();
- p.loadFromXML(pInStream);
- p.list(System.out);
- } catch (IOException e) {
- e.printStackTrace();
- }
xml文件如下:
[xhtml] view plain copy
- <?xml version="1.0" encoding="UTF-8" standalone="no"?>
- <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
- <properties>
- <comment>test</comment>
- <entry key="age">25</entry>
- <entry key="name">tinyfun</entry>
- <entry key="sex">man</entry>
- <entry key="title">software developer</entry>
- </properties>
3. 写入XML文件
[java] view plain copy
- Properties p = new Properties();
- p.setProperty("name","tinyfun");
- p.setProperty("age","25");
- p.setProperty("sex","man");
- p.setProperty("title","software developer");
- try{
- PrintStream fW = new PrintStream(new File("test.xml"));
- p.storeToXML(fW,"test");
- } catch (IOException e) {
- e.printStackTrace();
- }
4. 写入.properties文件
[java] view plain copy
- Properties p = new Properties();
- p.setProperty("name","tinyfun");
- p.setProperty("age","25");
- p.setProperty("sex","man");
- p.setProperty("title","software developer");
- try{
- PrintStream fW = new PrintStream(new File("test.properties"));
- p.list(fW ); }
- catch (IOException e) {
- e.printStackTrace();
- }
Java之Property类使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。