Search code examples
javaexceptionini4j

ini4j Read File Error


I am trying to use ini4j. But I am not able to read the file. The code:

ini = new Wini(new InputStreamReader(new FileInputStream("./setup.ini"), "UTF-8"));

But it is giving me the errors:

Unhandled exception type IOException
Unhandled exception type InvalidFileFormatException
Unhandled exception type UnsupportedEncodingException
Unhandled exception type FileNotFoundException

I already tried "C:\setup.ini" and "setup.ini" and "C:/setup.ini" I also tried:

ini = new Wini(new InputStreamReader(new FileInputStream(New File("./setup.ini")), "UTF-8"));

The Variable ini is properly declared:

Wini ini;

Any Ideas?


Solution

  • Simple Windows .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.");
      }
     }
    
    } 
    

    Writing to .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.");
     }
    
     }