用Java读取INI文件(带section的)

下面是我从一篇博文中转载过来的,在android中使用的时候发现转义字符有问题,修改如下,希望给其他朋友有所参考。

下面36~37行的地方应该改为:// --->  \\

最终是通过Properties来实现的,比直接字符流来读取多了很多便利. 可以直接定位到域,根据键就能拿到值.而不是遍历判断来取值

[java]  view plain copy
  1. /*        
  2.  *     IniReader.java    
  3.  *     用Java读取INI文件(带section的)    
  4.  *     示例:        
  5.  *           tmp.IniReader   reader   =   new   tmp.IniReader("E://james//win.ini");    
  6.  *           out.println(reader.getValue("TestSect3",   "kkk   6"));    
  7.  */  
  8.   
  9. import java.io.BufferedReader;  
  10. import java.io.FileReader;  
  11. import java.io.IOException;  
  12. import java.util.HashMap;  
  13. import java.util.Properties;  
  14.   
  15. public class IniReader {  
  16.   
  17.     protected HashMap sections = new HashMap();  
  18.     private transient String currentSecion;  
  19.     private transient Properties current;  
  20.   
  21.     public IniReader(String filename) throws IOException {  
  22.         BufferedReader reader = new BufferedReader(new FileReader(filename));  
  23.         read(reader);  
  24.         reader.close();  
  25.     }  
  26.   
  27.     protected void read(BufferedReader reader) throws IOException {  
  28.         String line;  
  29.         while ((line = reader.readLine()) != null) {  
  30.             parseLine(line);  
  31.         }  
  32.     }  
  33.   
  34.     private void parseLine(String line) {  
  35.         line = line.trim();  
  36.         if (line.matches("//[.*//]") == true) {  
  37.             secion = line.replaceFirst("//[(.*)//]""$1");  
  38.             properties = new Properties();  
  39.             sections.put(secion, properties);  
  40.         } else if (line.matches(".*=.*") == true) {  
  41.             if (properties != null) {  
  42.                 int i = line.indexOf('=');  
  43.                 String name = line.substring(0, i);  
  44.                 String value = line.substring(i + 1);  
  45.                 properties.setProperty(name, value);  
  46.             }  
  47.         }  
  48.     }  
  49.   
  50.     public String getValue(String section, String name) {  
  51.         Properties p = (Properties) sections.get(section);  
  52.   
  53.         if (p == null) {  
  54.             return null;  
  55.         }  
  56.   
  57.         String value = p.getProperty(name);  
  58.         return value;  
  59.     }  
  60.   
  61. }  


 ini文件如下:         [TestSect1]     kkk   1=VVVVVVVVVVV1     kkk   2=VVVVVVVVVVV2         [TestSect2]     kkk   3=VVVVVVVVVVV3     kkk   4=VVVVVVVVVVV4         [TestSect3]     kkk   5=VVVVVVVVVVV5     kkk   6=VVVVVVVVVVV6 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值