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();
    }
  }
}

 

目录
打赏
0
0
0
0
6
分享
相关文章
Minecraft配置文件参数说明(JAVA服务器篇)
Minecraft JAVA版服务器启动后会生成server.properties配置文件,位于minecraft_server/根目录下。该文件包含多项关键设置,如游戏模式(gamemode)、最大玩家数(max-players)、难度(difficulty)等。此文档详细说明了各配置项的功能与默认值,帮助用户高效管理服务器环境。
123 3
|
2月前
|
Java中执行命令并使用指定配置文件的最佳实践
通过本文的介绍,您可以了解如何在Java中使用 `ProcessBuilder`执行系统命令,并通过指定配置文件、设置环境变量和重定向输入输出流来控制命令的行为。通过这些最佳实践,可以确保您的Java应用程序在执行系统命令时更加健壮和灵活。
52 7
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
53 4
|
6月前
|
java与XML文件的读写
java与XML文件的读写
62 3
java读取配置文件数据
java读取配置文件数据
185 0
阿里巴巴-EasyExcel 基于Java的简单、省内存的读写Excel
该文章主要介绍了在Java应用中如何使用EasyExcel技术完成对Excel文件的导入和导出操作,包括环境搭建、基本概念、快速入门、进阶操作和综合应用等内容,并提供了相关代码示例和注意事项。
 阿里巴巴-EasyExcel 基于Java的简单、省内存的读写Excel
Java日志详解:日志级别,优先级、配置文件、常见日志管理系统ELK、日志收集分析
Java日志详解:日志级别,优先级、配置文件、常见日志管理系统、日志收集分析。日志级别从小到大的关系(优先级从低到高): ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF 低级别的会输出高级别的信息,高级别的不会输出低级别的信息
Java SpringBoot 加载 yml 配置文件中字典项
Java SpringBoot 加载 yml 配置文件中字典项
90 0
Java文件操作,让你的代码更“有型”!读写、复制、删除全解析!
【6月更文挑战第27天】在Java中进行文件操作是程序基础功能之一,涉及读写、复制和删除。使用`FileReader/FileWriter`进行文本文件的读写,如示例所示,通过`try-with-resources`保证资源释放。文件复制利用`FileInputStream/FileOutputStream`,而删除文件则依赖`File`的`delete()`方法,确保条件安全执行。这些标准库类提供了高效且健壮的文件管理能力。
77 0