View Javadoc
1   package com.randomnoun.common;
2   
3   /* (c) 2013 randomnoun. All Rights Reserved. This work is licensed under a
4    * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
5    */
6   
7   import java.io.File;
8   import java.io.InputStream;
9   import java.io.FileInputStream;
10  import java.io.IOException;
11  import java.io.LineNumberReader;
12  import java.io.InputStreamReader;
13  import java.text.ParseException;
14  
15  import java.util.HashMap;
16  import java.util.Map;
17  import java.util.Set;
18  
19  
20  /** Windows .ini file parser
21   * 
22   * Properties without explicit groups are recorded with a null group
23   * 
24   * 
25   */
26  public class IniFile {
27      
28      
29  
30  
31  	/** Map of property groups to property name-value pairs */
32  	private Map<String, Map<String, String>> properties;
33  	
34  	public IniFile() {
35  		properties = new HashMap<String, Map<String, String>>();
36  	
37  	}
38  	
39  	public void load(File file) throws IOException, ParseException {
40  		InputStream is = new FileInputStream(file);
41  		load(is);
42  	}
43  	
44  	public void load(InputStream is) throws IOException, ParseException {
45  		LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
46  		try {
47  			String line = lnr.readLine();
48  			String group = null;
49  			while(line!=null) {
50  				// @TODO handle newlines 
51  				line = line.trim();
52  				if (line.startsWith(";")) {
53  					// comment; ignore
54  				} else if (line.startsWith("[")) {
55  					if (line.endsWith("]")) {
56  						group = line.substring(1, line.length()-1);
57  					} else {
58  						throw new ParseException("Line " + lnr.getLineNumber() + ": invalid .ini group declaration", 0);
59  					}
60  				} else if (line.contains("=")) {
61  					int pos = line.indexOf("=");
62  					String name = line.substring(0, pos);
63  					String value = line.substring(pos+1);
64  					Map<String, String> propMap = properties.get(group);
65  					if (propMap==null) {
66  						propMap = new HashMap<String, String>();
67  						properties.put(group, propMap);
68  					}
69  					propMap.put(name, value);
70  				}
71  				
72  				line=lnr.readLine();
73  			}
74  		} finally {
75  			try {
76  				is.close();	
77  			} catch (IOException ioe) {
78  				// ignore
79  			}
80  		}
81  	}
82  	
83  	public String get(String group, String key) {
84  		Map<String, String> propMap = properties.get(group);
85  		if (propMap==null) { return null; }
86  		return propMap.get(key);
87  	}
88  	
89  	public Set<String> getGroups() {
90  		return properties.keySet();
91  	}
92  	
93  	public Set<String> getGroupKeys(String group) {
94  		Map<String, String> propMap = properties.get(group);
95  		if (propMap==null) { return null; }
96  		return propMap.keySet();
97  	}
98  	
99  }