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 Map<String, String> readAllProperties()
throws FileNotFoundException, IOException {
// 保存所有的键值
Map<String, String> map = new HashMap<String, String>();
Enumeration<?> en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty(key);
map.put(key, Property);
}
Iterator<Entry<String, String>> mapEntryItr = map.entrySet().iterator();
while (mapEntryItr.hasNext()) {
Map.Entry<String, String> 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;
}
}
properties read write example
最新推荐文章于 2016-06-30 15:50:02 发布