本文共 1985 字,大约阅读时间需要 6 分钟。
public class PropertyUtil01 { private static Properties props = null; public static void main(String[] args) { PropertyUtil01 p; try { p = new PropertyUtil01(); props = readProperties(); System.out.println(readValue("name")); System.out.println(readValue("pwd")); setValue("url", "jdbc:db:xxx"); System.out.println(); System.out.println(p.readAllProperties()); } catch (IOException e) { e.printStackTrace(); } } public MapreadAllProperties() throws FileNotFoundException, IOException { // 保存所有的键值 Map map = new HashMap (); Enumeration en = props.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String Property = props.getProperty(key); map.put(key, Property); } Iterator > mapEntryItr = map.entrySet().iterator(); while (mapEntryItr.hasNext()) { Map.Entry maEntry = mapEntryItr.next(); System.out.println(maEntry.getValue()); } return map; } public static String readValue(String key) throws IOException { return props.getProperty(key); } public static void setValue(String key, String value) throws IOException { OutputStream fos = null; try { // e.g. D:\workspace\j2seTest1\bin\properties\config.properties fos = new FileOutputStream(PropertyUtil01.class.getClassLoader() .getResource("properties/").toURI().getPath() + "config.properties"); props.setProperty(key, value); props.store(fos, "comments: last update"); } catch (URISyntaxException e) { e.printStackTrace(); } finally { fos.close(); } } public static Properties readProperties() throws IOException { Properties prop = new Properties(); InputStream fis = null; try { // e.g. D:\workspace\j2seTest1\bin\properties\config.properties fis = new FileInputStream(PropertyUtil01.class.getClassLoader() .getResource("properties/").toURI().getPath() + "config.properties"); prop.load(fis); } catch (URISyntaxException e1) { e1.printStackTrace(); } finally { fis.close(); } return prop; }}
转载地址:http://xwili.baihongyu.com/