在项目中经常用到各种配置文件,有.properties的,也有.xml格式的
都可以通过java.utils.Property类进行处理。
1. 读取.properties文件
- 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();
- p.list(System.out) ;
- while(enu.hasMoreElements())
- {
- String thisKey = (String)enu.nextElement();
- System.out.println("key="+thisKey);
- System.out.println("value="+p.getProperty(thisKey));
- }
.properties测试文件内容如下:
name = tinyfun
age = 25
sex = man
title = software developer
2. 读取XML文件
- 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文件如下:
- <?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文件
- 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文件
- 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();
- }