Dave's Brain

Browse - Programming Tips - What is a very simple way to read an .ini file?

Date: 2014dec15
Language: Java

Q.  What is a very simple way to read an .ini file?

A.
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; class IniFile { private static Pattern secpat = Pattern.compile("\\[(.+)\\]"); private static Pattern vpat = Pattern.compile("([^=]+)=(.*)"); // LinkedHashMap preserves order public static LinkedHashMap<String, String> load(final String strIniFile) { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String section = ""; try { InputStream in = new FileInputStream(strIniFile); BufferedReader br = new BufferedReader(new InputStreamReader(in), 5 * 1024); String line; while ((line = br.readLine()) != null) { Matcher secMatcher = secpat.matcher(line); if (secMatcher.matches()) { section = secMatcher.group(1); continue; } Matcher vMatcher = vpat.matcher(line); if (vMatcher.matches()) { map.put(section + "." + vMatcher.group(1), vMatcher.group(2)); continue; } } in.close(); } catch(IOException e) { // Handle problem } return map; } } // Does not handle comments or blank lines

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.