Enjoy life; enjoy java

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  1 Posts :: 0 Stories :: 0 Comments :: 0 Trackbacks

2006年7月6日 #

 

  1 /*  
  2
  3 * @(#) IniReader.java 
  4
  5 * Created on 2004-10-14 
  6
  7 * Created by James Fancy 
  8
  9 */
 
 10
 11 import  java.io.BufferedReader; 
 12
 13 import  java.io.FileReader; 
 14
 15 import  java.io.IOException; 
 16
 17 import  java.util.HashMap; 
 18
 19 import  java.util.Properties; 
 20
 21 /**  
 22
 23 @author  James Fancy 
 24
 25 */
 
 26
 27 public   class  IniReader 
 28
 29 protected  HashMap sections  =   new  HashMap(); 
 30
 31 private   transient  String currentSecion; 
 32
 33 private   transient  Properties current; 
 34
 35 public  IniReader(String filename)  throws  IOException 
 36
 37 BufferedReader reader  =   new  BufferedReader( new  FileReader(filename)); 
 38
 39 read(reader); 
 40
 41 reader.close(); 
 42
 43 }
 
 44
 45 protected   void  read(BufferedReader reader)  throws  IOException 
 46
 47 String line; 
 48
 49 while  ((line  =  reader.readLine())  !=   null
 50
 51 parseLine(line); 
 52
 53 }
 
 54
 55 }
 
 56
 57 protected   void  parseLine(String line) 
 58
 59 line  =  line.trim(); 
 60
 61 if  (line.matches( " \\[.*\\] " )) 
 62
 63 //  如果是 JDK 1.4(不含1.4)以下版本,修改为 
 64
 65 //  if (line.startsWith("[") && line.endsWith("]")) { 
 66
 67 if  (current  !=   null
 68
 69 sections.put(currentSecion, current); 
 70
 71 }
 
 72
 73 currentSecion  =  line.replaceFirst( " \\[(.*)\\] " " $1 " ); 
 74
 75 //  JDK 低于 1.4 时 
 76
 77 //  currentSection = line.substring(1, line.length() - 1); 
 78
 79 current  =   new  Properties(); 
 80
 81 }
  else   if  (line.matches( " .*=.* " )) 
 82
 83 //  JDK 低于 1.4 时 
 84
 85 //  } else if (line.indexOf('=') >= 0) { 
 86
 87 int  i  =  line.indexOf( ' = ' ); 
 88
 89 String name  =  line.substring( 0 , i); 
 90
 91 String value  =  line.substring(i  +   1 ); 
 92
 93 current.setProperty(name, value); 
 94
 95 }
 
 96
 97 }
 
 98
 99 public  String getValue(String section, String name) 
100
101 Properties p  =  (Properties) sections.get(section); 
102
103 if  (p  ==   null
104
105 return   null
106
107 }
 
108
109 String value  =  p.getProperty(name); 
110
111 return  value; 
112
113 }
 
114
115 }
 
116
117 示例: 
118
119 public   static   void  main(String[] args)  throws  IOException 
120
121 IniReader reader  =   new  IniReader( " E:\\james\\win.ini " ); 
122
123 System.out.println(reader.getValue( " MCI Extensions.BAK " " asf " )); 
124
125 }
 
126
127
posted @ 2006-07-06 10:49 Freax 阅读(767) | 评论 (0)编辑 收藏