报价
HOME
报价
正文内容
gw nand.ini Java基础之如何读取INI格式文件
发布时间 : 2024-10-18
作者 : 小编
访问数量 : 23
扫码分享至微信

Java基础之如何读取INI格式文件

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

本篇文章主要讲述一下INI文件格式以及如何使用java读写INI格式的文件。欢迎大家关注头条号“路人宅”。

文件格式

节(section)

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

[section]

键(key)

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

name=value

注释(comment)

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

; comment text

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

[section1]

key1=value1

[section2]

key2=value2

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

package com.yoodb.core.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 路人宅

* 来源:头条号"路人宅"

*/

public class INIUtil {

private static final Logger logger = Logger.getLogger(INIUtil.class.getName());

/**

* 用linked hash map 来保持有序的读取

*

*/

final LinkedHashMap<String,LinkedHashMap> coreMap = new LinkedHashMap<String, LinkedHashMap>();

/**

* 当前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;

}

MapchildMap = coreMap.get(currentSection);

childMap.put(key, value);

}

/**

* 增加Section

* @param section

*/

void addSection(String section) {

if (!coreMap.containsKey(section)) {

currentSection = section;

LinkedHashMapchildMap = new LinkedHashMap();

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 Mapget(String section){

return coreMap.containsKey(section) ? coreMap.get(section) : null;

}

/**

* 获取这个配置文件的节点和值

* @return

*/

public LinkedHashMap<String, LinkedHashMap> 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("魔兽世界=最强套装");

va = ini.builder(ini, section);

System.out.println("变动后结果值:\r\n" + va);

}

private String builder(INIUtil ini,String section){

Setkeys = 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();

}

}

注意:在增加或修改base_auth.ini文件内容时不要存在空格以及特殊字符,否则无法读取文件值。

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

默认固定值:

白百合 = 白百何首发声承认离婚

卓伟 = 原名韩炳江,被誉为“中国内地第一狗仔”

变动后结果值:

白百合 = 白百何首发声承认离婚

卓伟 = 原名韩炳江,被誉为“中国内地第一狗仔”

魔兽世界 = 最强套装

C++之INI配置文件读写注释库 inicpp 介绍

【简单易用-包含inicpp.hpp头文件即可】

一个头文件(header-file-only)搞定INI文件读写、甚至进行注释。

跨平台,并且用法极其简单。MIT license,从此配置INI文件就像喝水。

【 注:对您有帮助的话,Star或Issues为项目维护提供动力,感谢。】 - by offical of JN-inicpp project.

一、库下载

https://github.com/dujingning/inicpp:GitHub - dujingning/inicpp: The INI header-only library for Modern C++ supports reading and writing, even writing comments. It is cross-platform and can be used on multiple operating systems.

或者

https://gitee.com/dujingning/inicpp:inicpp: 一个头文件(header-file-only)搞定INI文件读写、甚至进行写注释。跨平台,并且用法极其简单。MIT license,从此配置INI文件就像喝水。[注:对您有帮助的话,Star或Issues为项目维护提供动力,感谢。] - by offical of JN-inicpp parser project.

二、库使用

1.读取INI文件示例

```cpp

#include "inicpp.cpp"

int main()

{

// Load and parse the INI file.

inicpp::iniReader _ini("config.ini");

std::cout << _ini["rtsp"]["port"] << std::endl;

}

```

2.写入INI文件示例

```cpp

#include "inicpp.cpp"

int main()

{

// Load and parse the INI file.

inicpp::iniReader _ini("config.ini");

_ini.modify("rtsp","port","554");

std::cout << _ini["rtsp"]["port"] << std::endl;

}

```

3.注释INI文件示例

```cpp

#include "inicpp.cpp"

int main()

{

// Load and parse the INI file.

inicpp::iniReader _ini("config.ini");

_ini.modify("rtsp","port","554","this is the listen port for rtsp server");

std::cout << _ini["rtsp"]["port"] << std::endl;

}

```

4.转换Value值toString()、toInt()、toDouble()

```cpp

#include "inicpp.cpp"

int main()

{

// Load and parse the INI file.

inicpp::iniReader _ini("config.ini");

_ini.modify("rtsp","port","554","this is the listen port for rtsp server");

std::cout << _ini["rtsp"]["port"] << std::endl;

// Convert to string, default is string

std::string http_port_s = _ini["http"].toString("port");

std::cout << "to string:\thttp.port = " << http_port_s << std::endl;

// Convert to double

double http_port_d = _ini["http"].toDouble("port");

std::cout << "to double:\thttp.port = " << http_port_d << std::endl;

// Convert to int

int http_port_i = _ini["http"].toInt("port");

std::cout << "to int:\t\thttp.port = " << http_port_i << std::endl;

}

```

5.全部功能用例见 example/main.cpp. 使用g++编译 `g++ -I../ -std=c++11 main.cpp -o iniExample` .

```cpp

#include "inicpp.hpp"

#include <iomanip>

/* compile: g++ -I../ -std=c++11 main.cpp -o iniExample */

int main()

{

// Load the INI file.

inicpp::IniManager _ini("config.ini");

// Check if the key exists.

if (!_ini["rtsp"].isKeyExist("port"))

{

std::cout << "rtsp.port is not exist!" << std::endl;

}

// Modify or add key-value pairs.

_ini.modify("rtsp", "port", "554");

// Use key-value pairs directly.

std::string rtsp_port = _ini["rtsp"]["port"];

// You can write section-key-value.

_ini.modify("rtsp", "port", "554");

// Add a comment.

_ini.modify("rtsp", "port", "554", "this is the listen port for http server");

// Modify the comment.

_ini.modifyComment("rtsp", "port", "this is the listen port for rtsp server ***");

// Try to modify or add more.

_ini.modify("math", "PI", "3.1415926", "This is pi in mathematics.");

// You have obtained the key-value pair and saved it to your config file.

std::cout << "to string:\trtsp.port = " << _ini["rtsp"]["port"] << std::endl;

// Convert to string, default is string

std::string http_port_s = _ini["math"].toString("PI");

std::cout << "to string:\tmath.PI = " << http_port_s << std::endl;

// Convert to double

double http_port_d = _ini["math"].toDouble("PI");

std::cout << "to double:\tmath.PI = " << std::setprecision(10) << http_port_d << std::endl;

// Convert to int

int http_port_i = _ini["math"].toInt("PI");

std::cout << "to int:\t\tmath.PI = " << http_port_i << std::endl;

return 0;

}

```

* g++编译命令过程示例

```bash

[root@jn inicpp]# ls

example inicpp.hpp LICENSE README.md

[root@jn inicpp]# cd example/

[root@jn example]# grep -Rn g++

main.cpp:4:/* compile: g++ -I../ -std=c++11 main.cpp -o iniExample */

[root@jn example]# g++ -I../ -std=c++11 main.cpp -o iniExample

[root@jn example]# ls

iniExample main.cpp

[root@jn example]# ./iniExample

rtsp.port is not exist!

to string: rtsp.port = 554

to string: math.PI = 3.1415926

to double: math.PI = 3.1415926

to int: math.PI = 3

[root@jn example]# ls

config.ini iniExample main.cpp

[root@jn example]# cat config.ini

[rtsp]

;this is the listen port for rtsp server ***

port=554

[math]

;This is pi in mathematics.

PI=3.1415926

[root@jn example]#

```

相关问答

界面上突然出现了desktop .ini 这个文件,可以删除吗?急!!-ZOL问答

shaqixiang因为你开启了显示系统隐藏文件.不想让它出现你关闭此选项就可以了...在“Windows”、“Windows\System”、“Windows\Fonts”、“Windows\T...

key .ini 是什么文件,能删么?-ZOL问答

ng5552979一般最好不要去动它,不过如果你要删除的话,下面几个可以删除:1、系统临时文件:[C:\WINDOWS\Temp]。2、系统升级备份文件:[C:\WINDOWS\ServiceP...

win0界面desktop .ini 可以删除吗-ZOL问答

desktop.ini文件属于文件夹的配置文件,用户可以删除,删除后不会影响文件夹,只是会让文件夹恢复为默认设置。另外desktop.ini文件并不是病毒文件,当然有些病毒文...

红警2地图编辑器 INI 编辑怎么用?

打开触发编辑器,点击新建触发名字随便取,最好取giveme所属参战方选治安,其他什么的不要动将对话框转到条件一栏,事件类型选13,参数值为0(如果你要过一段时...

西门子plc的梯形图中的辅助继电器的括号中加一个N是什么意思...

[回答]下降沿就是由前面的语句由通至断时,后面的线圈有动作I0.0Q0.0---II-----INI--------------(S)I0.0由1变0是Q0.0被置位下降沿就是由前面的...

【千字文全篇(带拼音、解释)】作业帮

[回答]天地玄黄(tiāndìxuánhuáng),宇宙洪荒(yǔzhòuhónghuāng).玄,天也;黄,地之色也;洪,大也;荒,远也;宇宙广大无边.日月盈昃(rìyuè...

文件夹后缀变成.exe 怎么处理?-ZOL问答

wubin8008这个是你中了U盘文件夹exe病毒,现在U盘病毒90%是kido病毒,kido病毒虽然很多杀软能杀,但是都没处理掉他的母体。而那些文件夹并没有真的丢失,只是被...

msword.lnk是什么?-ZOL问答

ccwle080305.exe,衍生病毒文件,使用bat批处理删除原文件。添加启动项,以达到随机启动的目的。将衍生DLL文件插入IE中进行病毒文件下载与信息收集的目的。通...

然后就是读取配置文件失败:Version .ini ,这是为什么-ZOL问答

登陆CF.提示Version.ini信息读取失败我把防火墙关了,再进游戏,正常了.总结:有时候Version.ini信息读取失败可能是防火墙导致的下面是一些其他的解决办法出...

开机电脑显示:grub4dos,怎么办?

进入grub4dos后输入命令find--set-root/ntldrchainloader/ntldrboot注意每行后都有回车。试一下吧!开机的时候按住F8键要放,你会看到操作系...

 作家海鸣威  刘晓粽 
王经理: 180-0000-0000(微信同号)
10086@qq.com
北京海淀区西三旗街道国际大厦08A座
©2024  上海羊羽卓进出口贸易有限公司  版权所有.All Rights Reserved.  |  程序由Z-BlogPHP强力驱动
网站首页
电话咨询
微信号

QQ

在线咨询真诚为您提供专业解答服务

热线

188-0000-0000
专属服务热线

微信

二维码扫一扫微信交流
顶部