java读取ini格式的文件

已上图就是ini文件的格式,经常在配置文件中用到。

1、核心代码:

/**
     * 去除ini文件中的注释,以";"或"#"开头,顺便去除UTF-8等文件的BOM头
     * @param source
     * @return
     */
    private static String removeIniComments(String source){
        String result = source;

        if(result.contains(";")){
            result = result.substring(0, result.indexOf(";"));
        }

        if(result.contains("#")){
            result = result.substring(0, result.indexOf("#"));
        }

        return result.trim();
    }

    public static Map<String,Object> readIni(String filename){
        Map<String,List<String>> listResult=new HashMap<>();
        Map<String,Object> result=new HashMap();
        String globalSection = "global";

        File file = new File(filename);
        BufferedReader reader=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String str = null;
            String currentSection = globalSection; //处理缺省的section
            List<String> currentProperties = new ArrayList<>();
            boolean lineContinued = false;
            String tempStr = null;

            //一次读入一行(非空),直到读入null为文件结束
            //先全部放到listResult<String, List>中
            while ((str = reader.readLine()) != null) {
                str = removeIniComments(str).trim(); //去掉尾部的注释、去掉首尾空格

                if("".equals(str)||str==null){
                    continue;
                }

                //如果前一行包括了连接符‘\‘
                if(lineContinued == true){
                    str = tempStr + str;
                }

                //处理行连接符‘\‘
                if(str.endsWith("\\")){
                    lineContinued = true;
                    tempStr = str.substring(0,str.length()-1);
                    continue;
                }else {
                    lineContinued = false;
                }

                //是否一个新section开始了
                if(str.startsWith("[") && str.endsWith("]")){
                    String newSection = str.substring(1, str.length()-1).trim();

                    //如果新section不是现在的section,则把当前section存进listResult中
                    if(!currentSection.equals(newSection)){
                        listResult.put(currentSection, currentProperties);
                        currentSection = newSection;

                        //新section是否重复的section
                        //如果是,则使用原来的list来存放properties
                        //如果不是,则new一个List来存放properties
                        currentProperties=listResult.get(currentSection);
                        if(currentProperties==null){
                            currentProperties = new ArrayList<>();
                        }
                    }
                }else{
                    currentProperties.add(str);
                }
            }
            //把最后一个section存进listResult中
            listResult.put(currentSection, currentProperties);

            reader.close();

        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        //整理拆开name=value对,并存放到MAP中:
        //从listResult<String, List>中,看各个list中的元素是否包含等号“=”,如果包含,则拆开并放到Map中
        //整理后,把结果放进result<String, Object>中
        for(String key : listResult.keySet()){
            List<String> tempList = listResult.get(key);

            //空section不放到结果里面
            if(tempList==null||tempList.size()==0){
                continue;
            }

            if(tempList.get(0).contains("=")){ //name=value对,存放在MAP里面
                Map<String, String> properties = new HashMap<>();
                for(String s : tempList){
                    int delimiterPos = s.indexOf("=");
                    //处理等号前后的空格
                    properties.put(s.substring(0,delimiterPos).trim(), s.substring(delimiterPos+1, s.length()).trim());
                }
                result.put(key, properties);
            }else{ //只有value,则获取原来的list
                result.put(key, listResult.get(key));
            }
        }

        return result;

    }
    

2、测试代码:

Map<String, Object> ini = readIni("E:/testini.ini");
        for(String k : ini.keySet()){
            System.out.println(k + ini.get(k));
        }

        System.out.println("获取单个值:"+((Map<String, String>)ini.get("section2")).get("key3"));

原文地址:https://www.cnblogs.com/vinpho/p/10177372.html

时间: 2024-08-03 03:58:25

java读取ini格式的文件的相关文章

Java读取UTF-8格式文件第一行出现乱码——问号“?”及解决 And Java读带有BOM的UTF-8文件乱码原因及解决方法

测试例子: Java读取UTF-8的txt文件第一行出现乱码"?"及解决 test.txt文件内容: 1 00:00:06,000 --> 00:00:06,010 <b>Allerleirauh</b> (2012) <i>dTV - Das Erste - 20. Januar 2013</i> 2 00:00:10,280 --> 00:00:12,680 Was geh?rt zu einer guten Suppe?

Java读取Level-1行情dbf文件极致优化(2)

最近架构一个项目,实现行情的接入和分发,需要达到极致的低时延特性,这对于证券系统是非常重要的.接入的行情源是可以配置,既可以是Level-1,也可以是Level-2或其他第三方的源.虽然Level-1行情没有Level-2快,但是作为系统支持的行情源,我们还是需要优化它,使得从文件读取,到用户通过socket收到行情,端到端的时延尽可能的低.本文主要介绍对level-1行情dbf文件读取的极致优化方案.相信对其他的dbf文件读取应该也有借鉴意义. Level-1行情是由行情小站,定时每隔几秒把d

java处理excel-xlsx格式大文件的解决方案

1.第一次读取7M左右的ecxel文件,使用poi 库实现,参考了下面的博文. http://www.cnblogs.com/chenfool/p/3632642.html 使用上面的方法在 下面WorkbookFactory.create()这里会出现内存溢出的错误,将eclipse的参数调整为-Xmx3072m,仍然会出现这个错误. fis = new FileInputStream(file); book = WorkbookFactory.create(fis); 应该是因为上面的方法使

Java读取Level-1行情dbf文件极致优化(3)

最近架构一个项目,实现行情的接入和分发,需要达到极致的低时延特性,这对于证券系统是非常重要的.接入的行情源是可以配置,既可以是Level-1,也可以是Level-2或其他第三方的源.虽然Level-1行情没有Level-2快,但是作为系统支持的行情源,我们还是需要优化它,使得从文件读取,到用户通过socket收到行情,端到端的时延尽可能的低.本文主要介绍对level-1行情dbf文件读取的极致优化方案.相信对其他的dbf文件读取应该也有借鉴意义. Level-1行情是由行情小站,定时每隔几秒把d

java 读取并且显示 txt 文件

系统:mac os x 10.9 eclipse 在eclipse 中建立一个project, 命名为Cin_txt, Cin_txt的内容 test wang hello world 以下是输入的代码 import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Cin_txt { public static void main(String[] args) { Fil

hadoop用mutipleInputs实现map读取不同格式的文件

mapmap读取不同格式的文件这个问题一直就有,之前的读取方式是在map里获取文件的名称,按照名称不同分不同的方式读取,例如下面的方式 //取文件名称 InputSplit inputSplit = context.getInputSplit(); String fileName = ((FileSplit) inputSplit).getPath().toString(); if(fileName.contains("track")) { } else if(fileName.con

SHELL读取 ini 格式文件做配置文件

ini文件格式一般都是由节.键.值三部分组成 格式: [第一节 ] 第一个键 = 值 第二个键 = 第二个值 [第二节 ] 第一个键 = val1,val2,val3 例子: [COM] KINGGOO = kinggoo.com 其实这个作用没那么特别大,但多个shell如果每个配置信息都在shell文件里面写,懂的人还好,半懂+不仔细的人要如何改,改几个地方估 计脚本就不能运行了.所以这样单独哪出来比较好些,而且可以多个shell使用一个ini文件(与扩展名无关)来做配置也可以的.只需要在s

部分转 Java读取ini配置

转自: http://www.cnblogs.com/Jermaine/archive/2010/10/24/1859673.html 读取ini的配置的格式如下: [section1] key1=value1 [section2] key2=value2 .... 原blog中考虑: 其中可能一个Key对应多个value的情况. 代码如下: 1 import java.io.BufferedReader; 2 import java.io.FileReader; 3 import java.i

Java读取ini配置

软件151    陶涛 读取ini的配置的格式如下: 1 2 3 4 5 6 7 [section1] key1=value1 [section2] key2=value2 .... 其中可能一个Key对应多个value的情况. 代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46