黑马程序员__关于学习Properties的学习总结

来源:互联网 发布:酒店网络点评回复范文 编辑:程序博客网 时间:2024/05/17 03:49

                -------android培训java培训、期待与您交流! ----------

 

Properties 类表示了一个持久的属性集。
Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

一个属性列表可包含另一个属性列表作为它的“默认值”;
如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。

 

因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNames 或 list 方法,则该调用将失败。

 

load(Reader) / store(Writer, String) 方法按下面所指定的、简单的面向行的格式在基于字符的流中加载和存储属性。除了输入/输出流使用 ISO 8859-1 字符编码外,load(InputStream) / store(OutputStream, String) 方法与 load(Reader)/store(Writer, String) 对的工作方式完全相同。可以使用 Unicode 转义来编写此编码中无法直接表示的字符;转义序列中只允许单个 'u' 字符。可使用 native2ascii 工具对属性文件和其他字符编码进行相互转换。

此类是线程安全的:多个线程可以共享单个 Properties 对象而无需进行外部同步。

 

如何将文件中的键值数据存到集合中进行操作?

    1,用一个流和文件关联
    2,读取一行数据,将该行数据用“=”进行切割
    3,等号左边作为键,右边作为值,存入Properties集合中

import java.io.*;class PropertiesDemo{    public static void main(String[] args){        method();    }    public static void method(){       BufferedReader bufr = null;       Properties prop = new Properties ();       try{           bufr = new BufferedReader (new FileReader("info.ini"));           String line = null;           while((line=bufr.readLine())!=null){               String[] arr = line.split("=");               prop.setProperty(arr[0],arr[1]);            }           //prop.load(bufr); 功能和上面一样       }catch(IOException e){           System.out.println(e);       }finally{           try{                if(bufr!=null)                    bufr.close();           }catch(IOException e){                System.out.println(e);           }       }    }}

 

 如果将一个文件中的键值信息修改并保存 

会应用到load()方法和Store(FileOutputStream  fos,String str)方法

 

import java.io.*;class PropertiesDemo2{    public static void main(String[] args){         loadDemo();    }    public static void loadDemo(){       FileInputStream fis = null;       FileOutputStream fos = null;       Properties prop = new Properties ();       try{           fis = new FileInputStream ("info.ini");           prop.load(fis);  //将文件的键值信息存储到Properties对象中           prop.setProperty("jian","zhi");  //修改键值信息                      FileOutputStream  fos = new FileOutputStream ("info.ini");           prop.store(fos,"注释信息"); //将修改后的信息保存源文件                  }catch(IOException e){           System.out.println(e);       }finally{           try{                if(bufr!=null)                    bufr.close();           }catch(IOException e){                System.out.println(e);           }       }    }}


 

 

 

 

原创粉丝点击