properties文件
bookName = The Kite Runner price = 25.6 author = Khaled Hosseini简单实现properties解析
package com.mec.parser.test; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; public class TestForProperties { public static void main(String[] args) { Properties properties = new Properties(); InputStream is = Class.class.getResourceAsStream("/test.properties"); try { properties.load(is); Enumeration<Object> keys = properties.keys(); // 获取properties文件中的键集合 // Enumeration是一个泛型类,里面存储的是键值对数据集合 while(keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = properties.getProperty(key); System.out.println(key + " " + value); } } catch (IOException e) { e.printStackTrace(); } } }运行结果
author: Khaled Hosseini price: 25.6 bookName: The Kite Runner工具代码
package com.mec.util.parser; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; public class PropertiesParser { private static final Map<String, String> propertyMap = new HashMap<>(); public PropertiesParser() { } public static void loadProperties(String path) { InputStream is = PropertiesParser.class.getResourceAsStream(path); loadProperties(is); } public static void loadProperties(InputStream is) { Properties properties = new Properties(); try { properties.load(is); Set<Object> keySet = properties.keySet(); Iterator<Object> iterator = keySet.iterator(); while(iterator.hasNext()) { String key = (String) iterator.next(); String value = properties.getProperty(key); propertyMap.put(key, value); } } catch (IOException e) { e.printStackTrace(); } } public static Set<String> keySet() { return propertyMap.keySet(); } public static String value(String key) { return propertyMap.get(key); } }使用
工具测试代码
package com.mec.util.parser; public class TestForProperties { public static void main(String[] args) { PropertiesParser.loadProperties("/test.properties"); String bookName = String.valueOf(PropertiesParser.value("bookName")); System.out.println("书名:" + bookName); String authorName = String.valueOf(PropertiesParser.value("author")); System.out.println("作者:" + authorName); double price = Double.valueOf(PropertiesParser.value("price")); System.out.println("价格:" + price); } }运行结果
书名:The Kite Runner 作者:Khaled Hosseini 价格:25.6