96、java的IO操作-Properties

来源:互联网 发布:采购流程及优化 编辑:程序博客网 时间:2024/05/20 23:34
/* * Properties:属性集合类。是一个可以和IO流相结合使用的集合类。 * Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。  *  * 是Hashtable的子类,说明是一个Map集合。 */public class PropertiesDemo {public static void main(String[] args) {// 作为Map集合的使用// 下面这种用法是错误的,一定要看API,如果没有<>,就说明该类不是一个泛型类,在使用的时候就不能加泛型// Properties<String, String> prop = new Properties<String, String>();Properties prop = new Properties();// 添加元素prop.put("it002", "hello");prop.put("it001", "world");prop.put("it003", "java");// System.out.println("prop:" + prop);// 遍历集合Set<Object> set = prop.keySet();for (Object key : set) {Object value = prop.get(key);System.out.println(key + "---" + value);}}}/* * 特殊功能: * public Object setProperty(String key,String value):添加元素 * public String getProperty(String key):获取元素 * public Set<String> stringPropertyNames():获取所有的键的集合 */public class PropertiesDemo2 {public static void main(String[] args) {// 创建集合对象Properties prop = new Properties();// 添加元素prop.setProperty("张三", "30");prop.setProperty("李四", "40");prop.setProperty("王五", "50");// public Set<String> stringPropertyNames():获取所有的键的集合Set<String> set = prop.stringPropertyNames();for (String key : set) {String value = prop.getProperty(key);System.out.println(key + "---" + value);}}}/* * class Hashtalbe<K,V> { public V put(K key,V value) { ... } } *  * class Properties extends Hashtable { public V setProperty(String key,String * value) { return put(key,value); } } *//* * 这里的集合必须是Properties集合: * public void load(Reader reader):把文件中的数据读取到集合中 * public void store(Writer writer,String comments):把集合中的数据存储到文件 */public class PropertiesDemo3 {public static void main(String[] args) throws IOException {// myLoad();myStore();}private static void myStore() throws IOException {// 创建集合对象Properties prop = new Properties();prop.setProperty("林青霞", "27");prop.setProperty("武鑫", "30");prop.setProperty("刘晓曲", "18");//public void store(Writer writer,String comments):把集合中的数据存储到文件Writer w = new FileWriter("name.txt");prop.store(w, "helloworld");w.close();}private static void myLoad() throws IOException {Properties prop = new Properties();// public void load(Reader reader):把文件中的数据读取到集合中// 注意:这个文件的数据必须是键值对形式Reader r = new FileReader("prop.txt");prop.load(r);r.close();System.out.println("prop:" + prop);}}

原创粉丝点击