JavaでINIファイルを解析する最も簡単な方法は何ですか?
質問
Javaのレガシーアプリケーションのドロップイン置換を書いています。要件の1つは、古いアプリケーションが使用していたiniファイルを新しいJavaアプリケーションにそのまま読み込む必要があることです。このiniファイルの形式は、コメント用の文字として#を使用して、ヘッダーセクションとkey = valueのペアを持つ一般的なWindowsスタイルです。
JavaのPropertiesクラスを使用しようとしましたが、もちろん、異なるヘッダー間で名前の衝突がある場合は機能しません。
質問は、このINIファイルを読み取り、キーにアクセスする最も簡単な方法は何ですか?
解決
使用したライブラリは ini4j です。軽量で、iniファイルを簡単に解析します。また、設計目標の1つは標準Java APIのみを使用することであったため、10,000個の他のjarファイルへの難解な依存関係は使用しません
これは、ライブラリの使用方法の例です。
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));
他のヒント
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 ));
}
}
apacheクラス HierarchicalINIConfiguration :
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()){
String sectionName = sectionNames.next().toString();
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
Commons Configurationには、多数のランタイム依存関係があります。少なくとも、 commons-lang および commons-logging が必要です。使用している内容によっては、追加のライブラリが必要になる場合があります(詳細については前のリンクを参照してください)。
または標準のJava APIでは、 javaを使用できます。 .util.Properties :
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
props.load(in);
}
18行で、 java.util.Properties
を拡張して複数のセクションに解析します:
public static Map<String, Properties> parseINI(Reader reader) throws IOException {
Map<String, Properties> result = new HashMap();
new Properties() {
private Properties section;
@Override
public Object put(Object key, Object value) {
String header = (((String) key) + " " + value).trim();
if (header.startsWith("[") && header.endsWith("]"))
return result.put(header.substring(1, header.length() - 1),
section = new Properties());
else
return section.put(key, value);
}
}.load(reader);
return result;
}
別のオプションは Apache Commons Config には、 INIファイル。いくつかの実行時の依存関係がありますが、INIファイルの場合はCommonsコレクションのみが必要です。 lang、およびロギング。
プロジェクトでCommons Configを使用し、そのプロパティとXML構成を使用しました。非常に使いやすく、非常に強力な機能をサポートしています。
JINIFileを試すことができます。 DelphiからのTIniFileの翻訳ですが、Java用です
個人的には Confucious を好みます。
外部の依存関係を必要とせず、非常に小さく、わずか16Kであり、初期化時にiniファイルを自動的にロードします。例:
Configurable config = Configuration.getInstance();
String host = config.getStringValue("host");
int port = config.getIntValue("port");
new Connection(host, port);
これはこれと同じくらい簡単です.....
//import java.io.FileInputStream;
//import java.io.FileInputStream;
Properties prop = new Properties();
//c:\\myapp\\config.ini is the location of the ini file
//ini file should look like host=localhost
prop.load(new FileInputStream("c:\\myapp\\config.ini"));
String host = prop.getProperty("host");