Ini读取操作

Ini是什么

INI 就是英initialization”的头三个字母的缩写;当然INI file的后缀名也不一定是”.ini”也可以是”.cfg”,”.conf ”或者是”.txt”。

为什么要用ini?

程序没有任何配置文件,那么它对外是全封闭的,一旦程序需要修改一些参数必须要修改程序代码本身并重新编译,为了让程序出厂后还能根据需要进行必要的配置,所以要用配置文件;配置文件有很多种,如INI配置文件,XML配置文件,cfg配置文件,还有就是可以使用系统注册表等。本文主要讲解ini的读写操作!

INI文件的格式很简单,最基本的三个要素是:parameters,sections和comments。

parameter

name = value

section如下所示:

[section]

注释实例如下:

;comments text //只占一行

一.读写ini

ini读取

    /**成员属性设置*/
    final static String filePath = System.getProperty("user.dir");
    final static String fileOrith=filePath+"/Config.ini";

    /**本項目下运行使用这两段代码**/
//    String substring = filePath.substring(0, filePath.lastIndexOf("\\"));
//    String fileOrith=substring+"/Config.ini";

    private static Properties properties =new Properties();

    FileInputStream fis = null; // 读

    OutputStream fos ;

    /**
     * ini配置读取
     */
    public IniReader() {

        try {
            fis = new FileInputStream(fileOrith);
            properties.load(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

ini设置值/获取值

 public String getProperty(String key)
    {
        Object object = properties.get(key);
        return object.toString();
    }

    public void setProperty(String key, String value){
        try {
            fos = new FileOutputStream(fileOrith);// 加载读取文件流
            properties.setProperty(key, value);
            properties.store(fos, null);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方法测试

  public static void main(String[] args) {
        String filePath = System.getProperty("user.dir");
        String substring = filePath.substring(0, filePath.lastIndexOf("\\"));
        System.out.println(substring);


        IniReader ini = new IniReader();
        System.out.println(ini.getProperty("ClientUrl"));

    }

ini格式

;客户端配置
[Client]
;客户端版本号
version=0001
;设备号
devNum=6405

二.读写ini(含section段)

从ini配置文件中读取变量的值

 public static String readCfgValue(String file, String section, String variable, String defaultValue) throws IOException {
        String strLine, value = "";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        boolean isInSection = false;
        try {
            while ((strLine = bufferedReader.readLine()) != null) {
                strLine = strLine.trim();
                strLine = strLine.split("[;]")[0];
                Pattern p;
                Matcher m;
                p = Pattern.compile("\\[\\w+]");//Pattern.compile("file://[//s*.*//s*//]");
                m = p.matcher((strLine));
                if (m.matches()) {
                    p = Pattern.compile("\\[" + section + "\\]");//Pattern.compile("file://[//s*" + section + "file://s*//]");
                    m = p.matcher(strLine);
                    if (m.matches()) {
                        isInSection = true;
                    } else {
                        isInSection = false;
                    }
                }
                if (isInSection == true) {
                    strLine = strLine.trim();
                    String[] strArray = strLine.split("=");
                    if (strArray.length == 1) {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable)) {
                            value = "";
                            return value;
                        }
                    } else if (strArray.length == 2) {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable)) {
                            value = strArray[1].trim();
                            return value;
                        }
                    } else if (strArray.length > 2) {
                        value = strArray[0].trim();
                        if (value.equalsIgnoreCase(variable)) {
                            value = strLine.substring(strLine.indexOf("=") + 1).trim();
                            return value;
                        }
                    }
                }
            }
        } finally {
            bufferedReader.close();
        }
        return defaultValue;
    }

修改ini配置文件中变量的值

public static boolean writeCfgValue(String file, String section, String variable, String value) throws IOException {
        String fileContent, allLine, strLine, newLine, remarkStr = "";
        String getValue = null;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        boolean isInSection = false;
        boolean canAdd = true;
        fileContent = "";
        try {

            while ((allLine = bufferedReader.readLine()) != null) {
                allLine = allLine.trim();
                strLine = allLine.split(";")[0];
                Pattern p;
                Matcher m;
                p = Pattern.compile("\\[\\w+]");
                m = p.matcher((strLine));
                if (m.matches()) {
                    p = Pattern.compile("\\[" + section + "\\]");
                    m = p.matcher(strLine);
                    if (m.matches()) {
                        isInSection = true;
                    } else {
                        isInSection = false;
                    }
                }
                if (isInSection == true) {
                    strLine = strLine.trim();
                    String[] strArray = strLine.split("=");
                    getValue = strArray[0].trim();
                    if (getValue.equalsIgnoreCase(variable)) {
                        newLine = getValue + "=" + value;
                        fileContent += newLine;
                        while ((allLine = bufferedReader.readLine()) != null) {
                            fileContent += "\r\n" + allLine;
                        }
                        bufferedReader.close();
                        canAdd = false;
                        System.out.println(fileContent);
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false));
                        bufferedWriter.write(fileContent);
                        bufferedWriter.flush();
                        bufferedWriter.close();

                        return true;
                    }

                }
                fileContent += allLine + "\r\n";
            }
            if (canAdd) {
                String str = variable + "=" + value;
                fileContent += str + "\r\n";
                System.out.println(fileContent);
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, false));
                bufferedWriter.write(fileContent);
                bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            bufferedReader.close();
        }
        return false;
    }

方法测试


**路径*/
    final static String filePath = System.getProperty("user.dir")+"\\Config.ini";
    /**段名称*/
    final  static String section = "Client";
    /**要获取的变量名称*/
    final  static String variable = "version";

    @Test
    public  void IniReader(){

        try {  // 0为默认值 当ini中此value值不存在 则默认为0
            String s = ConfigurationFile.readCfgValue(filePath, section, variable, "0");
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


  转载请注明: java_百科网 Ini读取操作

 上一篇
java日志来历说明 java日志来历说明
java 日志一点不详细讲解日志简单介绍Log4j 1996年 Apache 创建得java日志包 是Apache基金会项目中的一员。Apache基金会还曾经建议sun引入Log4j到java的标准库中,但Sun拒绝了 Log4j 中要输
2019-06-13
下一篇 
java基础_小记篇 java基础_小记篇
java基础集合篇1.hashmap结构;什么对象能做为key 答:可以是任意对象或数据类型 但是做为key的数据有如下要求: Map集合存储数据的主要目的是为了查找 而List集合是为了输出 自己定义的类如果要想实现对象比
2019-05-10