java ini是什么文件_用Java解析INI文件的最简单方法是什么?

只需80行:

package windows.prefs;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class IniFile {

private Pattern  _section  = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );

private Pattern  _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );

private Map< String,

Map< String,

String >>  _entries  = new HashMap<>();

public IniFile( String path ) throws IOException {

load( path );

}

public void load( String path ) throws IOException {

try( BufferedReader br = new BufferedReader( new FileReader( path ))) {

String line;

String section = null;

while(( line = br.readLine()) != null ) {

Matcher m = _section.matcher( line );

if( m.matches()) {

section = m.group( 1 ).trim();

}

else if( section != null ) {

m = _keyValue.matcher( line );

if( m.matches()) {

String key   = m.group( 1 ).trim();

String value = m.group( 2 ).trim();

Map< String, String > kv = _entries.get( section );

if( kv == null ) {

_entries.put( section, kv = new HashMap<>());

}

kv.put( key, value );

}

}

}

}

}

public String getString( String section, String key, String defaultvalue ) {

Map< String, String > kv = _entries.get( section );

if( kv == null ) {

return defaultvalue;

}

return kv.get( key );

}

public int getInt( String section, String key, int defaultvalue ) {

Map< String, String > kv = _entries.get( section );

if( kv == null ) {

return defaultvalue;

}

return Integer.parseInt( kv.get( key ));

}

public float getFloat( String section, String key, float defaultvalue ) {

Map< String, String > kv = _entries.get( section );

if( kv == null ) {

return defaultvalue;

}

return Float.parseFloat( kv.get( key ));

}

public double getDouble( String section, String key, double defaultvalue ) {

Map< String, String > kv = _entries.get( section );

if( kv == null ) {

return defaultvalue;

}

return Double.parseDouble( kv.get( key ));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值