在 Java 中解析 INI 文件的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/190629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the easiest way to parse an INI file in Java?
提问by Mario Ortegón
I am writing a drop-in replacement for a legacy application in Java. One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application. The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the character for commenting.
我正在编写 Java 中遗留应用程序的替代品。要求之一是旧应用程序使用的 ini 文件必须按原样读入新的 Java 应用程序。这个ini文件的格式是常见的windows风格,有标题部分和键=值对,使用#作为注释字符。
I tried using the Properties class from Java, but of course that won't work if there is name clashes between different headers.
我尝试使用 Java 中的 Properties 类,但是如果不同标头之间存在名称冲突,那当然不起作用。
So the question is, what would be the easiest way to read in this INI file and access the keys?
所以问题是,读取这个 INI 文件并访问密钥的最简单方法是什么?
采纳答案by Mario Ortegón
The library I've used is ini4j. It is lightweight and parses the ini files with ease. Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API
我使用的库是ini4j。它是轻量级的,可以轻松解析 ini 文件。此外,它不使用对 10,000 个其他 jar 文件的深奥依赖,因为设计目标之一是仅使用标准 Java API
This is an example on how the library is used:
这是一个关于如何使用库的示例:
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));
回答by John Meagher
Another option is Apache Commons Configalso has a class for loading from INI files. It does have some runtime dependencies, but for INI files it should only require Commons collections, lang, and logging.
另一种选择是Apache Commons Config也有一个用于从INI 文件加载的类。它确实有一些运行时依赖项,但对于 INI 文件,它应该只需要 Commons 集合、语言和日志记录。
I've used Commons Config on projects with their properties and XML configurations. It is very easy to use and supports some pretty powerful features.
我已经在具有属性和 XML 配置的项目上使用了 Commons Config。它非常易于使用并支持一些非常强大的功能。
回答by Peter
Or with standard Java API you can use java.util.Properties:
或者使用标准 Java API,您可以使用java.util.Properties:
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(path)) {
props.load(in);
}
回答by user50217
Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:
这是一个简单但功能强大的示例,使用 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 has a number of runtime dependencies. At a minimum, commons-langand commons-loggingare required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).
Commons Configuration 有许多运行时依赖项。至少需要commons-lang和commons-logging。根据您使用它的用途,您可能需要额外的库(有关详细信息,请参阅上一个链接)。
回答by tshepang
As mentioned, ini4jcan be used to achieve this. Let me show one other example.
正如提到的,ini4j可以用来实现这一目标。让我再举一个例子。
If we have an INI file like this:
如果我们有这样的 INI 文件:
[header]
key = value
The following should display value
to STDOUT:
以下应显示value
到 STDOUT:
Ini ini = new Ini(new File("/path/to/file"));
System.out.println(ini.get("header", "key"));
Check the tutorialsfor more examples.
查看教程以获取更多示例。
回答by Andreas Norman
You could try JINIFile. Is a translation of the TIniFile from Delphi, but for java
你可以试试 JINIFile。是来自 Delphi 的 TIniFile 的翻译,但用于 java
回答by Aerospace
As simple as 80 lines:
就像 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 ));
}
}
回答by Mark
I personally prefer Confucious.
我个人更喜欢孔子。
It is nice, as it doesn't require any external dependencies, it's tiny - only 16K, and automatically loads your ini file on initialization. E.g.
很好,因为它不需要任何外部依赖项,它很小 - 只有 16K,并在初始化时自动加载您的 ini 文件。例如
Configurable config = Configuration.getInstance();
String host = config.getStringValue("host");
int port = config.getIntValue("port");
new Connection(host, port);
回答by hoat4
In 18 lines, extending the java.util.Properties
to parse into multiple sections:
在 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;
}
回答by Desmond
It is just as simple as this.....
就这么简单......
//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");