Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse ini file with sections in Java?

Tags:

java

parsing

ini

Here is a sample ini file:

[link#1]
alias=My Link 1
link=https://www.yandex.ru/

[link#2]
alias=My Link 2
link=https://mail.ru/

[link#3]
alias=My Link 3
link=http://point.md/ru/

I've seen how to parse it, but the keys are the same, and I need to get this into lets say ArrayList<LinkObject> . Does anyone know a good solution for this? Or shall we format the .ini file differently?

like image 323
Filip Luchianenco Avatar asked Jan 06 '16 15:01

Filip Luchianenco


1 Answers

I can suggest you ini4j. This is small and very easy to use library. Just download files or include dependency into your maven config:

<dependency>
   <groupId>org.ini4j</groupId>
   <artifactId>ini4j</artifactId>
   <version>0.5.4</version>
</dependency>

Now to load .ini file just do:

Wini ini = new Wini(new File("your file path"));

Examples of usage:

//output names of all sections    
Collection<Profile.Section> list = ini.values();
for(Profile.Section section : list){
    System.out.println(section.getName());
}

//fetch and output option value
String value = ini.fetch("link#1", "alias");
System.out.println(value);

//output keys of all options of one section
Profile.Section section = ini.get("link#1");
for(String key : section.keySet()){
   System.out.println(key);
}
like image 77
Ken Bekov Avatar answered Sep 17 '22 05:09

Ken Bekov