使用javaini对.ini文件进行操作

.ini文件由节、键、值组成。

[section]
参数(键=值)
name=value

ini文件中的注解使用分号(;)表示。在分号后面的文字,直到该行的结尾都是注解。在使用之前先把org.dtools.javaini的jar包中导入到项目中。

.ini文件的创建

  //新建一个ini文件的对象
  IniFile iniFile = new BasicIniFile();
  //新建一个section password为section的名称
  IniSection dataSection = new BasicIniSection("password");
  //将section添加到新建的ini文件中
  iniFile.addSection(dataSection);
  //新建文件
  File file = new File("D://my.ini");
  //将.ini文件写入指定的路径中
  IniFileWriter iniFileWriter = new IniFileWriter(iniFile,file);
  iniFileWriter.write();

得到指定的.ini文件中的所有内容

 File file = new File("D://my.ini");
 IniFile iniFile = new BasicIniFile();
 IniFileReader rad =  new IniFileReader(iniFile,file); 
 //读取文件 此处应该捕获或者抛出一个异常
 rad.read();
 //获得ini文件中第一个section
IniSection iniSection = iniFile.getSection(0);
 //得到这个section中所有的key值
 Collection<String> collection = iniSection.getItemNames();
   for (String coll: collection) {
        IniItem iniItem = iniSection.getItem(coll);
        //得到key值对应的value
        String value = iniItem.getValue();
 }

在指定的.ini文件中根据key值获取value值

 File file = new File("D://my.ini");
 IniFile iniFile = new BasicIniFile();
 IniFileReader rad =  new IniFileReader(iniFile,file);
 //读取文件 此处应该捕获或者抛出一个异常
 rad.read();
 //根据section名称获取section
 IniSection iniSection = iniFile.getSection("password");
 //获取该section中指定的key值所对应的value值
 IniItem iniItem = iniSection.getItem("sssss");
  String delVal = iniItem.getValue();

修改.ini文件中指定的key的内容

 File file = new File("D://my.ini");
 IniFile iniFile = new BasicIniFile();
 IniFileReader rad =  new IniFileReader(iniFile,file);
 IniFileWriter wir = new IniFileWriter(iniFile,file); 
 rad.read();
 IniSection iniSection = iniFile.getSection("password"); 
 //一定不要新建一个IniItem对象
 IniItem iniItem = iniSection.getItem(text); 
 //修改key值对应的value值
 iniItem.setValue(val);
 wir.write();

在.ini文件中根据key值删除数据

 File file = new File("D://my.ini");
 IniFile iniFile = new BasicIniFile();
 IniFileReader rad =  new IniFileReader(iniFile,file);
 IniFileWriter wir = new IniFileWriter(iniFile,file); 
 rad.read();
 IniSection iniSection = iniFile.getSection("password"); 
 IniItem iniItem = iniSection.getItem("aaaa");
 iniSection.removeItem(iniItem);

由于最近一直在用,所以简单的做一个总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值