Wednesday, December 4, 2013

How To Use Ini4j To Your Java Application

You can use ini4j to your project to make some changes on your application settings even without recompiling it. The ini4j tutorial can make you up and running using this library as well.

The first thing we want to do is to download the library and integrate it with our favorite IDE. I recommend Eclipse IDE as you can easily add up additional libraries on your project without getting any trouble.


Simple Windows .ini file

This will be our very simple .ini file we are using throughout this tutorial. Please copy/paste this to your empty config/settings.ini file.

[main]
window-color = 00ffff
splash = true
[others]
version = 0.1
developer = Jim

Reading from .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
  try{
   Wini ini;
   /* Load the ini file. */
   ini = new Wini(new File("config/settings.ini"));
   /* Extract the window color value.*/
   int windowColor = ini.get("main", "window-color", int.class);
   /* Extract the splash screen status. */
   boolean splashScreen = ini.get("main", "splash", boolean.class);
   
   /* Show to user the output. */
   System.out.println("Your default window color is: " + windowColor);
   if(splashScreen){
    System.out.println("You have your splash screen activated.");
   }else{
    System.out.println("You have your splash disabled.");
   }
  } catch (InvalidFileFormatException e) {
   System.out.println("Invalid file format.");
  } catch (IOException e) {
   System.out.println("Problem reading file.");
  }
 }
The code above is pretty self explanatory and you could easly guess what the line of code does just by looking at it. We just basically read the settings.ini file from config directory and parse the windowColor value and splashScreen status to show to user.

Writing to windows .ini file


import java.io.File;
import java.io.IOException;

import org.ini4j.InvalidFileFormatException;
import org.ini4j.Wini;


public class Main {
 
 public static void main(String args[]){
 Wini ini;
 try {
  ini = new Wini(new File("config/settings.ini"));
  ini.put("main", "window-color", 000000);
  ini.put("main", "splash", false);
  ini.store();
 } catch (InvalidFileFormatException e) {
  System.out.println("Invalid file format.");
 } catch (IOException e) {
  System.out.println("Problem reading file.");
 }
  
 }
The code above couldn't get any simpler. We are basically overwriting the value of window-color and splash in main section. Then we invoke the Wini.store() method to update our ini file.

This simple tutorial can make you up and running using this wonderful library. Thank you for reading, have a nice day everybody!

No comments:

Post a Comment