| 
                         可以发现,在 Properties 构造方法初始化阶段,如果你给了一个自定义的 defaults ,当调用 Hashtable 的 get  方法没有搜索到元素值的时候,并且 defaults 也不等于空,那么就会进一步在 defaults 里面进行搜索元素值。 
方法测试如下: 
- public static void main(String[] args) { 
 -     Properties properties = new Properties(); 
 -     properties.setProperty("name1","张三"); 
 -     properties.setProperty("name2","张四"); 
 -     properties.setProperty("name3","张五"); 
 -     //将 properties 作为参数初始化到 newProperties 中 
 -     Properties newProperties = new Properties(properties); 
 -     newProperties.setProperty("name4","李三"); 
 -     //查询key中 name1 的值 
 -     System.out.println("查询结果:" + properties.getProperty("name1")); 
 - } 
 
  
输出结果: 
通过key查询结果:张三 
load方法(加载配置文件) 
load 方法,表示将 properties 文件以输入流的形式加载文件,并且提取里面的键、值对,将键值对元素添加到 map 中去。 
打开 Properties 的 load 方法,源码如下: 
- public synchronized void load(InputStream inStream) throws IOException { 
 -     //读取文件流 
 -     load0(new LineReader(inStream)); 
 - } 
 
  
load0 方法,源码如下: 
- private void load0 (LineReader lr) throws IOException { 
 -     char[] convtBuf = new char[1024]; 
 -     int limit; 
 -     int keyLen; 
 -     int valueStart; 
 -     char c; 
 -     boolean hasSep; 
 -     boolean precedingBackslash; 
 -  
 -     //一行一行的读取 
 -     while ((limit = lr.readLine()) >= 0) { 
 -         c = 0; 
 -         keyLen = 0; 
 -         valueStart = limit; 
 -         hasSep = false; 
 -  
 -         precedingBackslash = false; 
 -         //判断key的长度 
 -         while (keyLen < limit) { 
 -             c = lr.lineBuf[keyLen]; 
 -             if ((c == '=' ||  c == ':') && !precedingBackslash) { 
 -                 valueStart = keyLen + 1; 
 -                 hasSep = true; 
 -                 break; 
 -             } else if ((c == ' ' || c == 't' ||  c == 'f') && !precedingBackslash) { 
 -                 valueStart = keyLen + 1; 
 -                 break; 
 -             } 
 -             if (c == '') { 
 -                 precedingBackslash = !precedingBackslash; 
 -             } else { 
 -                 precedingBackslash = false; 
 -             } 
 -             keyLen++; 
 -         } 
 -         //获取值的起始位置 
 -         while (valueStart < limit) { 
 -             c = lr.lineBuf[valueStart]; 
 -             if (c != ' ' && c != 't' &&  c != 'f') { 
 -                 if (!hasSep && (c == '=' ||  c == ':')) { 
 -                     hasSep = true; 
 -                 } else { 
 -                     break; 
 -                 } 
 -             } 
 -             valueStart++; 
 -         } 
 -         //获取文件中的键和值参数 
 -         String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf); 
 -         String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf); 
 -         //调用 Hashtable 的 put 方法,将键值加入 map 中 
 -         put(key, value); 
 -     } 
 - } 
 
                          (编辑:52站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |