Properties是Hashtable的子类,Hashtable实现了Map。该类用于处理属性文件,key和value都是String类型。
a.properties文件:#表示注释
Java代码:
public void loadProperties() throws IOException { // 文件输入流 FileInputStream fis = new FileInputStream("a.properties"); // 创建Properties对象 Properties pros = new Properties(); // 加载文件 pros.load(fis); // 读取 String name = pros.getProperty("name"); String age = pros.getProperty("age"); // 输出到控制台 System.out.println(name); //Tom System.out.println(age); //18 // 关闭文件输入流 fis.close(); }Java代码:
public void storeProperties() throws IOException { // 文件输出流 FileOutputStream fos = new FileOutputStream("b.properties"); // 创建Properties对象 Properties pros = new Properties(); // 加载文件 pros.setProperty("gender", "male"); pros.setProperty("county","china"); pros.store(fos,"这是注释信息"); // 关闭文件输出流 fos.close(); }生成b.properties文件:
a.xml文件:
Java代码:
public void loadXml() throws IOException { // 文件输入流 FileInputStream fis = new FileInputStream("a.xml"); // 创建Properties对象 Properties pros = new Properties(); // 加载文件 pros.loadFromXML(fis); // 读取 String name = pros.getProperty("name"); String age = pros.getProperty("age"); // 输出到控制台 System.out.println(name); //Tom System.out.println(age); //18 // 关闭文件输入流 fis.close(); }
Java代码:
public void storeXml() throws IOException { // 文件输出流 FileOutputStream fos = new FileOutputStream("b.xml"); // 创建Properties对象 Properties pros = new Properties(); // 加载文件 pros.setProperty("gender", "male"); pros.setProperty("county","china"); pros.storeToXML(fos,"这是注释信息"); // 关闭文件输出流 fos.close(); }生成b.xml文件: