public class TestPropertes { public static void main(String[] args) { Properties pp = new Properties(); FileInputStream in = null; FileInputStream xmlin = null; FileOutputStream out = null; PrintStream ps = null; FileOutputStream xmlout = null; try { in = new FileInputStream("c:/Test.Properties"); } catch (FileNotFoundException e) { System.out.println("properties文件没有找到"); } try { pp.load(in); } catch (IOException e) { System.out.println(e + "调用load方法时出现异常"); } System.out.println(pp.getProperty("log4j.rootLogger")); System.out.println(pp.getProperty("log4j.appender.A")); System.out.println(pp.getProperty("log4j.appender.A1.layout")); try { ps = new PrintStream("c:/TestMemo.txt"); out = new FileOutputStream("c:/Test.Properties"); } catch (IOException e1) { System.out.println(e1 + "PrintStream creat Error"); } pp.list(ps); //将properties文件用list方法读取并存入ps文件中 //更改键值 Object o = pp.setProperty("log4j.rootLogger", "DEBUG,B"); //更改对应的HASHTABLE中的值,实际上文件中的值没变化 System.out.println(pp.getProperty("log4j.rootLogger")); pp.list(ps); //将键值更改后的properties文件用list方法读取并存入ps文件中.list会自动以追回的方式从原文件尾写入 System.out.println(o.getClass()); try { pp.store(out, ""); //调用store方法保存文件.注意文件格式 } catch (IOException e) { System.out.println(e + "stroe方法调用错误"); } try { xmlout = new FileOutputStream("c:/Test.xml"); } catch (IOException e) {} try { pp.storeToXML(xmlout, ""); //将properties文件保存为XML文档 } catch (IOException e) { e.printStackTrace(); } //--练习用java.util.properties类读取XML文档 try { xmlin = new FileInputStream("c:/Test.xml"); } catch (IOException e) {} try { pp.loadFromXML(xmlin); } catch (InvalidPropertiesFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(pp.getProperty("log4j.rootLogger")); pp.setProperty("log4j.rootLogger", "debug,a"); try { pp.storeToXML(xmlout, ""); //以追回方式添加到XML文档 } catch (IOException e) { e.printStackTrace(); } try { pp.store(out, "add file"); } catch (IOException e) { e.printStackTrace(); } } }