java 读写 ini 配置文件的示例代码

下面通过代码先看下java 读写 ini 配置文件,代码如下所示:

package org.fh.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 说明:ini文件读写操作工具类
 * 作者:FH Admin
 * from:fhadmin.cn
 */
public class IniFileUtil {
    /**
     * 从ini配置文件中读取变量的值
     * @param file         配置文件的路径
     * @param section      要获取的变量所在段名称
     * @param variable     要获取的变量名称
     * @param defaultValue 变量名称不存在时的默认值
     * @return 变量的值
     * @throws IOException 抛出文件操作可能出现的io异常
     */
    public static String readCfgValue(String file, String section, String variable, String defaultValue)
            throws IOException {
        String strLine, value = "";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(URLDecoder.decode(file, "UTF-8"))); //解决中文路径乱码
        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配置文件中变量的值
     * @param file     配置文件的路径
     * @param section  要修改的变量所在段名称
     * @param variable 要修改的变量名称
     * @param value    变量的新值
     * @throws IOException 抛出文件操作可能出现的io异常
     */
    public static boolean writeCfgValue(String file, String section, String variable, String value) throws IOException {
        String fileContent, allLine, strLine, newLine;
        String getValue = null;
        BufferedReader bufferedReader = new BufferedReader(new FileReader(URLDecoder.decode(file, "UTF-8"))); //解决中文路径乱码
        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;
                        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";
                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;
    }
    public static void main(String[] args) {
        try {
            /*;文件事例
            [Client]
            ;客户端版本号
            version=0001
            ;设备号
            devNum=6405*/
            String value = IniFileUtil.readCfgValue("L:/a.ini", "Client", "devNum", "1");
            System.out.println(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

补充:下面看下java 读取ini配置文件

在maven项目中的pom.xml中配置:

<dependency>
    <groupId>org.ini4j</groupId>
    <artifactId>ini4j</artifactId>
    <version>0.5.4</version>
</dependency>

env.ini文件:

[dev]
url="dev-url"
user="dev-user"
password="dev-password"

[testing]
url=""
user=""
password=""

代码:

import org.ini4j.Ini;
import org.ini4j.Profile;
import org.ini4j.Wini;
import java.io.File;
import java.util.Map;
import java.util.Set;
public class IniUtils {
    public static void main(String[] args) {
        try {
            readIni();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    private static void readIni() throws Exception{
        Wini ini = new Wini(new File("yourPath/env.ini"));
        // read
        Ini.Section section = ini.get("dev");
        String url = section.get("url");
        String user = section.get("user");
        String password = section.get("password");
        System.out.println(url);
        System.out.println(user);
        System.out.println(password);
        // or just use java.util.Map interface
        Map<String, String> map = ini.get("dev");
        String url1 = map.get("url");
        String user1 = map.get("user");
        String password1 = map.get("password");
        System.out.println(url1);
        System.out.println(user1);
        System.out.println(password1);
        // get all section names
        // Set<String> sectionNames = ini.keySet();
        // for(String sectionName: sectionNames) {
        //   Profile.Section section1 = ini.get(sectionName);
           // }
        // write
        ini.put("sleepy", "age", 55);
        ini.put("sleepy", "weight", 45.6);
        ini.store();
    }
}

参考:

http://ini4j.sourceforge.net/tutorial/OneMinuteTutorial.java.html
http://ini4j.sourceforge.net/tutorial/IniTutorial.java.html

到此这篇关于java 读写 ini 配置文件的文章就介绍到这了,更多相关java 读写 ini文件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 利用weixin-java-miniapp生成小程序码并直接返回图片文件流的方法

    有时候我们可能需要在其他的网页上展示我们自己的小程序中某些页面的小程序码,这种时候,我们需要用到小程序的生成小程序码的相关接口. 工具选型 我们仍然选用简单方便的weixin-java-miniapp来完成此功能. 项目配置 详见我们的另一篇文章点此进入 生成小程序码的相关类型 小程序码的其他生成方式以及相关类型在这篇文章点此进入中介绍的较为详细,此处不再赘述,以下仅以生成不限制张数的这种类型来做一个示例. 生成小程序码图片 先获取小程序的service实例wxMaService. 再获取二维码

  • Java读写ini文件代码示例

    本文实例主要实现Java读写ini文件,具体如下,代码中有详细注释. 在java中,配置文件一般主要是两种形式:xml文件或者property文件.但大部分人都习惯使用ini文件,而且ini文件的分节以及注释功能,比起xml,也是易懂易用的. 实例代码: package com.epoint.tools; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStream; im

  • 使用Java Minio搭建自己的文件系统详解

    目录 前言 1.Minio介绍 2.Minio安装与启动 3.Minio控制台创建存储桶 4.存储桶权限 5.控制台实现文件的上传与下载 6.使用Springboot与Minio整合实现文件的增删查改 6.1.创建项目 6.2.添加依赖 6.3.创建自定义属性与配置类 6.4.功能实现 6.4.1.文件上传 6.4.2.文件下载 6.4.3.查询全部文件 6.4.4.删除指定文件 总结 前言 最近接了一个项目,甲方不愿意买服务器,但是呢,项目又必须要用文件功能.所以很巧,最近又刚好看到了Mini

  • 基于Java写minio客户端实现上传下载文件

    前言: 确保已经安装了minio的服务端 代码: pom.xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>7.0.2</version> </dependency> application.yml server: port:90 minio: url: http://10.69.94.140

  • java 读写 ini 配置文件的示例代码

    下面通过代码先看下java 读写 ini 配置文件,代码如下所示: package org.fh.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URLDecoder; import java.util.regex.

  • Python3读写ini配置文件的示例

    ini文件即Initialization File初始化文件,在应用程序及框架中常作为配置文件使用,是一种静态纯文本文件,使用记事本即可编辑. 配置文件的主要功能就是存储一批变量和变量值,在ini文件中使用[章(Section)]对变量进行了分组,基本格式如下. # filename: config.ini [user] name=admin password=123456 is_admin=true [mysql] host=10.10.10.10 port=3306 db=apitest u

  • Windows系统中C#读写ini配置文件的程序代码示例分享

    最近接触到INI配置文件的读写,虽然很久以前微软就推荐使用注册表来代替INI配置文件,现在在Visual Studio上也有专门的.Net配置文件格式,但是看来看去还是INI配置文件顺眼.事实上.Net的XML格式配置文件在功能上更加强大,我也更推荐大家使用这种类型的配置文件来进行.Net软件的开发,我之所以使用INI配置文件,无非是想尝一下鲜和个人习惯而已. C#本身没有提供访问INI配置文件的方法,但是我们可以使用WinAPI提供的方法来处理INI文件的读写,代码很简单!网上有大量现成的代码

  • Python实现读写INI配置文件的方法示例

    本文实例讲述了Python实现读写INI配置文件的方法.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import ConfigParser import os '''读写配置文件的类 [section] logpath = D:\log\ imageminsize = 200 ''' class ConfigFile: '''构造函数:初始化''' def __init__(self,fileName): fileName = unicode(fileNam

  • SpringBoot+Mybatis-Plus实现mysql读写分离方案的示例代码

    1. 引入mybatis-plus相关包,pom.xml文件 2. 配置文件application.property增加多库配置 mysql 数据源配置 spring.datasource.primary.jdbc-url=jdbc:mysql://xx.xx.xx.xx:3306/portal?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=

  • Java实现Redis哨兵的示例代码

    前言: 本文将采用文字+代码的方式,讲解redis版哨兵的实现,所有代码都将写在一个类中,每个属性和方法都会结合文字加以说明. 1. 哨兵(Sentinel)主要功能如下: 1.不时的监控redis节点是否良好运行,如果节点不可达就会对节点进行下线标识 2.如果被标识的是主节点,哨兵就会选举一个redis从(slave)节点成为新的主节点继续对外提供读写服务, 进而实现自动故障转移,保证系统的高可用. 3.在redis主节点 和 从节点 进行切换后,主节点配置文件master_redis.con

  • Java 读写Properties配置文件详解

    Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集.不过Properties有特殊的地方,就是它的键和值都是字符串类型. 2.Properties中的主要方法 (1)load(InputStream inStream) 这个方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象.如下面的代码:

  • C#中读写INI配置文件的方法

    在作应用系统开发时,管理配置是必不可少的.例如数据库服务器的配置.安装和更新配置等等.由于Xml的兴起,现在的配置文件大都是以xml文档来存储.比如Visual Studio.Net自身的配置文件Mashine.config,Asp.Net的配置文件Web.Config,包括我在介绍Remoting中提到的配置文件,都是xml的格式. 传统的配置文件ini已有被xml文件逐步代替的趋势,但对于简单的配置,ini文件还是有用武之地的.ini文件其实就是一个文本文件,它有固定的格式,节Section

  • C++读取配置文件的示例代码

    代码地址 https://github.com/gongluck/Code-snippet/tree/master/cpp/config 需求 开发中,读取配置文件信息必不可少.Windows平台有现成的API可用,也很方便.但是一旦项目迁移到Linux平台下,原先在Windows平台下的代码就全部作废.所以,实现一套跨平台的配置文件读取功能代码可以节省不少的劳动力. 实现 依赖于boost的ini_parser,可以实现跨平台读取ini格式的配置文件. // config.h /* * @Au

随机推荐