Home arrow static arrow Java Programming [Archive] - sample code to read/write INI file with section
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - sample code to read/write INI file with section
This topic has 4 replies on 1 page.

Posts:13
Registered: 3/4/99
sample code to read/write INI file with section  
Jul 28, 2004 1:05 PM



 
I was searching for some code which can read/write windows ini files in the forum, but no one is suitable for me. So I wrote the following class. It can browse the ini file, and update a certain key in a certain section. Hope it can save time for someone who is looking for the same thing as I did.

ini file:
[sqlserver]
password=pass
connections=50
username=jun
url=jdbc:microsoft:sqlserver://localhost:1433;database=northwind
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
[oracle]
password=mypass
connections=50
username=jun
url=jdbc:oracle:thin:@localhost:1521:MYGLOBAL
driver=oracle.jdbc.driver.OracleDriver

code:
import java.io.*;import java.util.*; public class INIHandler {	String filename;	// key: section name, value: a hashmap which has the name and value pair within this section	HashMap sectionMap; 	public INIHandler(String f) {		filename = f;		sectionMap = new HashMap();	} 	public void setProperty(String _section, String _name, String _value) {		HashMap map = (HashMap) sectionMap.get(_section);		map.put(_name, _value);	} 	public void removeProperty(String _section, String _name) {		HashMap map = (HashMap) sectionMap.get(_section);		map.remove(_name);	} 	public void saveSection() {		String outfile = filename; 		BufferedReader fr = null;		BufferedWriter fw = null;		try {			String line = "";			fw = new BufferedWriter(new FileWriter(outfile)); 			// Write original file to tempfile until section			try {				Iterator it = sectionMap.keySet().iterator();				while (it.hasNext()) {					String section = (String) it.next();					// Write header out					fw.write("[" + section + "]");					fw.newLine(); 					HashMap map = (HashMap) sectionMap.get(section);					Iterator iter = map.keySet().iterator();					while (iter.hasNext()) {						String name = (String) iter.next();						String value = (String) map.get(name);						// Write key-value pair out						fw.write(name + "=" + value);						fw.newLine();					}				}			} catch (NullPointerException a) {				// File might end before section is found			}		} catch (IOException e) {		} finally {			try {				fw.close();			} catch (Exception e) {			}		}	} 	public void loadSection() {		BufferedReader fs = null;		try {			String line;			String section = null;			HashMap map = null;			fs = new BufferedReader(new FileReader(filename));			while ((line = fs.readLine()) != null) {				// check for "[", if not this is a name-value pair				if (line.indexOf("[") == -1) {					String name;					String value;					if (line.trim().length() > 0) {						line = line.trim();						if (line.indexOf("=") > -1) {							name = line.substring(0, line.indexOf("=")).trim();							value = line.substring(line.indexOf("=") + 1,									line.length()).trim();						} else {							name = line.trim();							value = "";						}						map.put(name, value);					}				} else { // this is the section line					// the last section is over					if (map != null){						if (map.size() != 0) {							sectionMap.put(section, map);						}					}					line = line.trim();					section = line.substring(1, line.length() - 1);					map = new HashMap();				}			}			// add the last map			if (map.size() != 0) {				sectionMap.put(section, map);			}		} catch (FileNotFoundException f) {			// take care		} catch (IOException i) {			// take care		} catch (NullPointerException e) {			// Section was not found		} finally {			try {				fs.close();			} catch (Exception e) {				// take care			}		}	}		public void print() {		Iterator it = sectionMap.keySet().iterator();		while (it.hasNext()) {			String section = (String) it.next();			HashMap map = (HashMap) sectionMap.get(section);			Iterator iter = map.keySet().iterator();			while (iter.hasNext()) {				String name = (String) iter.next();				String value = (String) map.get(name);				System.out.println(section + " : " + name + " : " + value );			}		}	}		public static void main (String args[]) {		   INIHandler wini = new INIHandler("my.ini");     		   wini.loadSection();     //		   wini.print();		   wini.setProperty("oracle", "username", "test");     		   wini.setProperty("sqlserver", "password", "mypwd");      		   wini.saveSection();	}}
 

Posts:13
Registered: 3/4/99
Re: sample code to read/write INI file with section  
Jul 28, 2004 1:43 PM (reply 1 of 4)



 
modified version. can create new ini file now.

import java.io.*;import java.util.*; public class INIHandler {	String filename; 	// key: section name, value: map, which has the name and value pair within	// this section	HashMap sectionMap; 	// key: property name in the section, value: property value in the sectoin	HashMap newPairMap; 	public INIHandler(String f) {		filename = f;		sectionMap = new HashMap();	} 	public void setProperty(String _section, String _name, String _value) {		HashMap hMap = (HashMap) sectionMap.get(_section);		if (hMap == null) {			newPairMap = new HashMap();			newPairMap.put(_name, _value);			sectionMap.put(_section, newPairMap);		} else {			hMap.put(_name, _value);		}	} 	public void removeProperty(String _section, String _name) {		HashMap hMap = (HashMap) sectionMap.get(_section);		hMap.remove(_name);	} 	public void saveSection() {		String outfile = filename; 		BufferedReader fr = null;		BufferedWriter fw = null;		try {			String line = "";			fw = new BufferedWriter(new FileWriter(outfile)); 			// Write original file to tempfile until section			try {				Iterator it = sectionMap.keySet().iterator();				while (it.hasNext()) {					String section = (String) it.next();					// Write header out					fw.write("[" + section + "]");					fw.newLine(); 					HashMap map = (HashMap) sectionMap.get(section);					Iterator iter = map.keySet().iterator();					while (iter.hasNext()) {						String name = (String) iter.next();						String value = (String) map.get(name);						// Write key-value pair out						fw.write(name + "=" + value);						fw.newLine();					}				}			} catch (NullPointerException a) {				// File might end before section is found			}		} catch (IOException e) {		} finally {			try {				fw.close();			} catch (Exception e) {			}		}	} 	public void loadSection() {		BufferedReader fs = null;		try {			String line;			String section = null;			HashMap map = null;			fs = new BufferedReader(new FileReader(filename));			while ((line = fs.readLine()) != null) {				// check for "[", if not this is a name-value pair				if (line.indexOf("[") == -1) {					String name;					String value;					if (line.trim().length() > 0) {						line = line.trim();						if (line.indexOf("=") > -1) {							name = line.substring(0, line.indexOf("=")).trim();							value = line.substring(line.indexOf("=") + 1,									line.length()).trim();						} else {							name = line.trim();							value = "";						}						map.put(name, value);					}				} else { // this is the section line					// a new section begins					if (map != null) {						if (map.size() != 0) {							sectionMap.put(section, map);						}					}					line = line.trim();					section = line.substring(1, line.length() - 1);					map = new HashMap();				}			}			// add the last map			if (map.size() != 0) {				sectionMap.put(section, map);			}		} catch (FileNotFoundException f) {			// take care		} catch (IOException i) {			// take care		} catch (NullPointerException e) {			// Section was not found		} finally {			try {				fs.close();			} catch (Exception e) {				// take care			}		}	} 	public void print() {		Iterator it = sectionMap.keySet().iterator();		while (it.hasNext()) {			String section = (String) it.next();			HashMap map = (HashMap) sectionMap.get(section);			Iterator iter = map.keySet().iterator();			while (iter.hasNext()) {				String name = (String) iter.next();				String value = (String) map.get(name);				System.out.println(section + " : " + name + " : " + value);			}		}	} 	public static void main(String args[]) {		// test for a existing ini file		INIHandler wini = new INIHandler("my.ini");		wini.loadSection();//		wini.print();		wini.setProperty("oracle", "username", "test");		wini.setProperty("sqlserver", "password", "mypwd");		wini.saveSection(); 		// create a new ini file		wini = new INIHandler("new.ini");		wini.setProperty("oracle", "username", "test");		wini.setProperty("sqlserver", "password", "mypwd");		wini.saveSection(); 	}}
 

Posts:14,142
Registered: 99-04-02
Re: sample code to read/write INI file with section  
Jul 28, 2004 1:54 PM (reply 2 of 4)



 
nice, but there's a problem with it... what if my property name starts with a [, ... you'd treat that as a new section... you should, on saving, write an escape char first, like \[ (and
for slash escapes), then on read, check for the \ and trim it off...
 

Posts:1,657
Registered: 1/8/98
Re: sample code to read/write INI file with section  
Jul 28, 2004 8:43 PM (reply 3 of 4)



 
I can certainly see a need for wanting to read INI files, but unless there's some other non-Java program that needs to use them (or you're doing this as an exercise), Java has some much better (and easier, more flexible) methodologies for storing application settings and preferences - see java.util.prefs in the API.
 

Posts:13
Registered: 3/4/99
Re: sample code to read/write INI file with section  
Jul 29, 2004 8:01 AM (reply 4 of 4)



 
java.util.prefs package is great. I will use it instead of the ini file in my java application, if I knew it earlier.
 
This topic has 4 replies on 1 page.