免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2913 | 回复: 9
打印 上一主题 下一主题

ini 文件读写 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-16 16:46 |只看该作者 |倒序浏览
  1. package com.3a.util.paraconf;

  2. /**
  3. * Ini configuration file helper.
  4. * By 3a
  5. * 2007-1-16
  6. */

  7. import java.io.*;
  8. import java.util.*;
  9. import java.util.regex.*;
  10. import java.lang.reflect.*;
  11. import com.3a.test.FtpSection;

  12. public class ConfigFile implements ConfigFileListener {

  13.   String PATTERN_REM = "^#.*$";
  14.   String PATTERN_SECTION = "^\\[([^\\]]*).*$";
  15.   String PATTERN_PROPERTY = "(^[^#][^=]*)=(.*)$";

  16.   String _fileName = null;
  17.   ArrayList _sections = null;
  18.   ArrayList _listeners = null;

  19.   Class _sectionClass = ConfigFileSection.class;

  20.   public ConfigFile(String fileName) {

  21.     _fileName = fileName;
  22.     _sections = new ArrayList();
  23.     _listeners = new ArrayList();
  24.   }

  25.   public void setSectionType(Class sectionClass) {

  26.     _sectionClass = sectionClass;
  27.   }

  28.   public void addListener(ConfigFileListener listener){

  29.     _listeners.add(listener);
  30.   }

  31.   public void addSection(ConfigFileSection section){

  32.     _sections.add(section);
  33.   }

  34.   ConfigFileSection genSection(Constructor generator, String sectionName) throws InstantiationException, IllegalAccessException, InvocationTargetException {

  35.     Object[] args = { sectionName };
  36.     return (ConfigFileSection) generator.newInstance(args);
  37.   }

  38.   String parseSectionName(Pattern pattern, String line) {

  39.     Matcher matcher = pattern.matcher(line);
  40.     return matcher.matches() ? matcher.group(1) : null;
  41.   }

  42.   boolean parseProperty(Pattern pattern, String line, String[] property) {

  43.     boolean result = false;
  44.     Matcher matcher = pattern.matcher(line);

  45.     if (matcher.matches()){

  46.       property[0] = matcher.group(1);
  47.       property[1] = matcher.group(2);
  48.       result = true;
  49.     }
  50.     return result;
  51.   }

  52.   public boolean loadFromFile() {

  53.     boolean result = false;
  54.     String line = null;
  55.     String sectionName = null;
  56.     String[] property = new String[2];
  57.     ConfigFileSection section = null;
  58.     BufferedReader reader = null;
  59.     Pattern sectionPattern = Pattern.compile(PATTERN_SECTION);
  60.     Pattern propertyPattern = Pattern.compile(PATTERN_PROPERTY);
  61.     Pattern remPattern = Pattern.compile(PATTERN_REM);

  62.     try {

  63.       Class[] _param = { String.class };
  64.       Constructor generator = _sectionClass.getConstructor(_param);
  65.       reader = new BufferedReader(new FileReader(_fileName));

  66.       while ( (line = reader.readLine()) != null) {

  67.         // read comment
  68.         if (line == null || line.trim().length() == 0 || remPattern.matcher(line).matches()) continue;

  69.         // read section
  70.         else if ( (sectionName = parseSectionName(sectionPattern, line)) != null) {

  71.           section = genSection(generator, sectionName);
  72.           System.out.println("ConfigFile.loading section ... " + sectionName);
  73.           _sections.add(section);
  74.         }
  75.         // read properties
  76.         else if (section != null && parseProperty(propertyPattern, line, property))
  77.           section.addProperty(property[0], property[1]);
  78.       }

  79.       result = true;
  80.     }
  81.     catch (Exception e) {

  82.       e.printStackTrace();
  83.     }

  84.     try { reader.close(); } catch (Exception e) {}

  85.     return result;
  86.   }

  87.   public void save() throws IOException {

  88.     saveToFile(_fileName);
  89.   }

  90.   void fireOnSave(ConfigFileSection section, int index){

  91.     ConfigFileEvent event = new ConfigFileEvent(this, section, index);

  92.     for (int i = 0; i < _listeners.size(); i++) ((ConfigFileListener) _listeners.get(i)).onSave(event);
  93.   }

  94.   public boolean saveToFile(String fileName) throws IOException {

  95.     boolean result = false;
  96.     BufferedWriter writer = null;

  97.     try {

  98.       writer = new BufferedWriter(new FileWriter(fileName));

  99.       for (int i = 0; i < _sections.size(); i++){

  100.         fireOnSave((ConfigFileSection) _sections.get(i), i);
  101.         writer.write(_sections.get(i).toString());
  102.       }

  103.       writer.flush();
  104.       result = true;
  105.     }
  106.     catch (Exception e) {
  107.       e.printStackTrace();
  108.     }

  109.     try { writer.close(); } catch (Exception e) {}

  110.     return result;
  111.   }

  112.   public ConfigFileSection getSection(int index){

  113.     return (ConfigFileSection) _sections.get(index);
  114.   }

  115.   public int getSectionCount(){

  116.     return _sections != null ? _sections.size() : 0;
  117.   }

  118.   public void removeSection(String section){

  119.     ConfigFileSection tmp = null;
  120.     for (int i=0; i < _sections.size(); i++){

  121.       tmp = (ConfigFileSection) _sections.get(i);
  122.       if (section.equals(tmp.getName())){ _sections.remove(i); break; }
  123.     }
  124.   }

  125.   public ConfigFileSection getSection(String section) {

  126.     ConfigFileSection result = null, tmp = null;

  127.     for (int i=0; i < _sections.size(); i++){

  128.       tmp = (ConfigFileSection) _sections.get(i);
  129.       if (section.equals(tmp.getName())){ result = tmp; break; }
  130.     }
  131.     return result;
  132.   }

  133.   public void onSave(ConfigFileEvent event){

  134.     FtpSection section = (FtpSection) event.getSection();
  135.     if ( FtpSection.SECTION_MSC_ID.equals(section.getSectionType()) )
  136.       section.addProperty("Index", String.valueOf(event.getIndex()));
  137.   }

  138.   public static void main(String[] args) throws Exception {

  139.     //**
  140.     ConfigFile configFile = new ConfigFile("g:/ftp.ini");
  141.     configFile.setSectionType(FtpSection.class);
  142.     configFile.addListener(this);
  143.     configFile.loadFromFile();
  144.     FtpSection section = (FtpSection) configFile.getSection("HOST01");
  145.     System.out.println("UFO: "+section.getSectionType() +"," + section.getSectionDescribe());
  146.     section.addProperty("Name", "3a");
  147.     section.changeProperty("Passwd", "3a");
  148.     configFile.removeSection("Global");
  149.     configFile.saveToFile("e:/ftp.ini");
  150.     /**/
  151.   }
  152. }
复制代码

  1. package com.3a.util.paraconf;

  2. public interface ConfigFileListener {

  3.   public void onSave(ConfigFileEvent event);
  4. }
复制代码

[ 本帖最后由 awk就是awp加ak 于 2007-1-22 11:26 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2007-01-16 16:47 |只看该作者
  1. package com.3a.util.paraconf;

  2. import java.util.*;

  3. public class ConfigFileSection {

  4.   HashMap _data = null;
  5.   String _name = null;
  6.   String NEW_LINE = "\r\n";

  7.   public ConfigFileSection(){

  8.     _data = new HashMap();
  9.   }

  10.   public ConfigFileSection(String sectionName) {

  11.     this();
  12.     _name = sectionName;
  13.   }

  14.   public void setName(String name){

  15.     _name = name;
  16.   }

  17.   public String getName(){

  18.     return _name;
  19.   }

  20.   public String getProperty(String property){

  21.     return (String) _data.get(property);
  22.   }

  23.   public void addProperty(String property, String value){

  24.     _data.put(property, value);
  25.   }

  26.   public void changeProperty(String property, String value){

  27.     if (_data.containsKey(property)) _data.put(property, value);
  28.   }

  29.   public String toString(){

  30.     StringBuffer result = new StringBuffer(2000).append("[").append(_name).append("]").append(NEW_LINE);
  31.     String key;
  32.     for (Iterator keys = _data.keySet().iterator(); keys.hasNext(); ){

  33.       key = (String) keys.next();
  34.       result.append(key).append("=").append(_data.get(key)).append(NEW_LINE);
  35.     }

  36.     return result.toString();
  37.   }
  38. }
复制代码
  1. package com.3a.test;

  2. import com.3a.util.paraconf.ConfigFileSection;
  3. import com.3a.util.common.*;

  4. public class FtpSection extends ConfigFileSection {

  5.   static final String SECTION_GLOBAL_ID = "0";
  6.   static final String SECTION_SITE_ID = "1";
  7.   static final String SECTION_HOST_ID = "2";

  8.   static final String SECTION_GLOBAL = "Global";
  9.   static final String SECTION_HOST = "HOST";

  10.   static final String DESCRIBE_GLOBAL = "全局配置";
  11.   static final String DESCRIBE_SITE = "站点信息";
  12.   static final String DESCRIBE_HOST = "主机";

  13.   public FtpSection(String sectionName){

  14.     super(sectionName);
  15.   }

  16.   public String getSectionType() {

  17.     String name = getName();
  18.     return SECTION_GLOBAL.equals(name) ? SECTION_GLOBAL_ID : (name.startsWith(SECTION_HOST) ? SECTION_HOST_ID : SECTION_SITE_ID);
  19.   }

  20.   public String getSectionDescribe(){

  21.     String type = getSectionType();
  22.     return SECTION_GLOBAL_ID.equals(type) ? DESCRIBE_GLOBAL : (SECTION_HOST_ID.equals(type) ? DESCRIBE_HOST : DESCRIBE_SITE);
  23.   }
  24. }
复制代码
  1. package com.3a.util.paraconf;

  2. public class ConfigFileEvent {

  3.   ConfigFile _controller = null;
  4.   ConfigFileSection _section = null;
  5.   int _index;

  6.   public ConfigFileEvent(ConfigFile controller, ConfigFileSection section, int index) {

  7.     _controller = controller;
  8.     _section = section;
  9.     _index = index;
  10.   }

  11.   public int getIndex(){ return _index; }
  12.   public ConfigFile getController(){ return _controller; }
  13.   public ConfigFileSection getSection(){ return _section; }
  14. }
复制代码

[ 本帖最后由 awk就是awp加ak 于 2007-1-22 11:19 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2007-01-16 16:55 |只看该作者
欢迎大家测试,有问题找我 ^_^

论坛徽章:
0
4 [报告]
发表于 2007-01-16 17:48 |只看该作者
报错了,楼主。
Exception in thread "main" java.lang.NullPointerException
        at src.com.contrlfile.ConfigFile.main(ConfigFile.java:141)

那个INI文件学要写什么?

论坛徽章:
0
5 [报告]
发表于 2007-01-17 08:53 |只看该作者
NullPointer 啊,我猜是ini文件的格式。。我认为是如下格式。。

[section]
#comment
prop1=val1
prop2=val2


btw,有个地方效率不高,反复 compile,其实只需要 compile 一次。
把 parseSectionName 里面的 Pattern 对象提取出来,作为参数,由 loadFromFile() 传递。

论坛徽章:
0
6 [报告]
发表于 2007-01-17 18:16 |只看该作者
增加方法
int getSectionCount();
void removeSection(sectionName);

论坛徽章:
0
7 [报告]
发表于 2007-01-18 13:18 |只看该作者
增加方法,其中 sectionClass 是 ConfigFileSection 的子类。
void setSection(Class sectionClass);

ini.rar

2.72 KB, 下载次数: 51

论坛徽章:
0
8 [报告]
发表于 2007-01-19 17:52 |只看该作者
谢谢,晚上再看看。

论坛徽章:
0
9 [报告]
发表于 2007-01-22 09:46 |只看该作者
新增方法 ConfigFile.addListener()

论坛徽章:
0
10 [报告]
发表于 2007-01-22 09:50 |只看该作者
附件懒得更新了(附件只是为更懒的人做的),直接复制上面的代码好了 ^_^
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP