原创

Java读写 INI 格式文件详细说明

INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中,这种配置文件的文件扩展名多为INI,INI是英文“初始化”(initialization)的缩写,正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。

本篇文章主要讲述一下INI文件格式以及如何使用java读写INI格式的文件。如果对本站www.yoodb.com感兴趣,欢迎收藏素文宅。

文件格式

节(section)

节用方括号括起来,单独占一行,例如:

[section]

键(key)

键(key)又名属性(property),单独占一行用等号连接键名和键值,例如:

name=value

注释(comment)

注释使用英文分号(;)开头,单独占一行。在分号后面的文字,直到该行结尾都全部为注释,例如:

; comment text

读取ini的配置的格式如下:

[section1]
key1=value1
 
[section2]
key2=value2
…

具体实现读写INI格式文件的代码如下:

package com.yoodb.core.shiro.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
/**
 * @author 素文宅
 * 来源:www.yoodb.com
 */
public class INIUtil {
private static final Logger logger = Logger.getLogger(INIUtil.class.getName());
    
    /**
     * 用linked hash map 来保持有序的读取
     * 
     */
    final LinkedHashMap<String,LinkedHashMap<String, String>>  coreMap = new LinkedHashMap<String, LinkedHashMap<String,String>>();
    /**
     * 当前Section的引用
     */
    String currentSection = null;
     
/**
 * 读取
 * @param file 文件
 * @throws FileNotFoundException 
 */
public INIUtil(File file) throws FileNotFoundException {
this.init(new BufferedReader(new FileReader(file)));
}
/***
 * 重载读取
 * @param path 给文件路径
 * @throws FileNotFoundException 
 */
public INIUtil(String path) throws FileNotFoundException {
    this.init(new BufferedReader(new FileReader(path)));
}
/***
 * 重载读取
 * @param source ClassPathResource 文件,文件在resource 中时直接 new ClassPathResource("file name");
 * @throws IOException 
 */
public INIUtil(ClassPathResource source) throws IOException {
this(source.getFile());
}
 
    void init(BufferedReader bufferedReader){
    try {
    read(bufferedReader);
    } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException("IO Exception:" + e);
    }
    }
    /**
     * 读取文件
     * @param reader
     * @throws IOException
     */
    void read(BufferedReader reader) throws IOException {
String line = null;
while((line=reader.readLine())!=null) {
    parseLine(line);
}
    }
     
    /**
     * 转换
     * @param line
     */
    public void parseLine(String line) {
line = line.trim();
// 此部分为注释
if(line.matches("^\\#.*$")) {
    return;
}else if (line.matches("^\\[\\S+\\]$")) {
    // section
    String section = line.replaceFirst("^\\[(\\S+)\\]$","$1");
    addSection(section);
}else if (line.matches("^\\S+=.*$")) {
    // key ,value
    int i = line.indexOf("=");
    String key = line.substring(0, i).trim();
    String value =line.substring(i + 1).trim();
    addKeyValue(currentSection,key,value);
}
    }
 
 
    /**
     * 增加新的Key和Value
     * @param currentSection
     * @param key
     * @param value
     */
    void addKeyValue(String currentSection,String key, String value) {
if(!coreMap.containsKey(currentSection)) {
    return;
}
Map<String, String> childMap = coreMap.get(currentSection);
childMap.put(key, value);
    }
 
 
    /**
     * 增加Section
     * @param section
     */
    void addSection(String section) {
if (!coreMap.containsKey(section)) {
    currentSection = section;
    LinkedHashMap<String,String> childMap = new LinkedHashMap<String,String>();
    coreMap.put(section, childMap);
}
    }
     
    /**
     * 获取配置文件指定Section和指定子键的值
     * @param section
     * @param key
     * @return
     */
    public String get(String section,String key){
if(coreMap.containsKey(section)) {
    return  get(section).containsKey(key) ?  get(section).get(key): null;
}
return null;
    }
     
     
     
    /**
     * 获取配置文件指定Section的子键和值
     * @param section
     * @return
     */
    public Map<String, String> get(String section){
return  coreMap.containsKey(section) ? coreMap.get(section) : null;
    }
     
    /**
     * 获取这个配置文件的节点和值
     * @return
     */
    public LinkedHashMap<String, LinkedHashMap<String, String>> get(){
return coreMap;
    }
    
    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
String fileName = "conf/shiro_base_auth.ini";
    ClassPathResource cp = new ClassPathResource(fileName);
    INIUtil ini = null;
    try {
ini = new INIUtil(cp.getFile());
    } catch (IOException e) {
logger.error("加载文件出错", e);
    }
    String section = "base_auth";
    String va = ini.builder(ini, section);
    System.out.println("默认固定值:\r\n" + va);
    ini.parseLine("yoodb/**=user");
    va = ini.builder(ini, section);
    System.out.println("变动后结果值:\r\n" + va);
}
    
    private String builder(INIUtil ini,String section){
Set<String> keys = ini.get(section).keySet();
    StringBuffer sb = new StringBuffer();
    for (String key : keys) {
String value = ini.get(section, key);
sb.append(key).append(" = ")
.append(value).append("\r\n");
    }
    return sb.toString();
    }
     
}

shiro_base_auth.ini文件,因公司业务需要封装CAS-client因此写的内容默认信息如下:

[base_auth]
/shiro-cas=casFilter
/logout=logoutFilter
/users/**=user

注意:在增加或修改shiro_base_auth.ini文件内容时不要存在空格以及特殊字符。

执行测试,运行结果如下:

默认固定值:
/shiro-cas = casFilter
/logout = logoutFilter
/users/** = user
变动后结果值:
/shiro-cas = casFilter
/logout = logoutFilter
/users/** = user
yoodb/** = user
~阅读全文-人机检测~

微信公众号“Java精选”(w_z90110),专注Java技术干货分享!让你从此路人变大神!回复关键词领取资料:如Mysql、Hadoop、Dubbo、Spring Boot等,免费领取视频教程、资料文档和项目源码。微信搜索小程序“Java精选面试题”,内涵3000+道Java面试题!

涵盖:互联网那些事、算法与数据结构、SpringMVC、Spring boot、Spring Cloud、ElasticSearch、Linux、Mysql、Oracle等

评论

分享:

支付宝

微信