以前看到过Java操作Properties文件的类,自己写了个简单的操作ini文件的类,希望对有这方面需求的朋友有帮助。同时欢迎指正。
import java.io.*;
import java.util.*;
public class IniFile extends HashMap{
private String fileName;
public IniFile(String fileName) {
setFileName(fileName);
}
public void setFileName(String fileName){
try {
this.fileName = fileName;
if (!FileTools.isFileExist(fileName))
FileTools.write(" ",fileName);
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
ArrayList values = null;
while ( (line = in.readLine()) != null) {
if (isSection(line)){
values = new ArrayList();
System.out.println(line.substring(1, line.length() - 1));
put(line.substring(1, line.length() - 1), values);
}
else if (values!=null) {
int index = line.indexOf("=");
if(index>0){
String k = line.substring(0,index).trim();
String v = line.substring(index+1).trim();
System.out.println(k+" "+v);
String[] kv = {k,v};
values.add(kv);
}
}
}
in.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public boolean isSection(String line){
boolean result = false;
if(line!=null && line.startsWith("[") && line.endsWith("]"))
result = true;
return result;
}
public Iterator getSections(){
return keySet().iterator();
}
public String getValue(String section,String key,String defaultValue){
String result = defaultValue;
ArrayList res = (ArrayList)get(section);
if(res!=null){
Iterator its = res.iterator();
while(its.hasNext()){
String[] kv = (String[])its.next();
if(kv!=null && kv[0].equals(key))
return kv[1];
}
}
return result;
}
public void setValue(String section,String key,String value){
ArrayList res = (ArrayList)get(section);
if(res==null){
ArrayList ares = new ArrayList();
ares.add(new String[]{key,value});
put(section,ares);
}
else{
Iterator its = res.iterator();
while(its.hasNext()){
String[] kv = (String[])its.next();
if(kv!=null && kv[0].equals(key))
kv[1] = value;
}
}
}
public void delSection(String section){
remove(section);
}
/**
* save the content to file
*
* @throws IOException
*/
public void save() throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
Iterator its = getSections();
while (its.hasNext()) {
Object key = its.next();
out.println("["+key+"]");
ArrayList res = (ArrayList) get(key);
Iterator itss = res.iterator();
while (itss.hasNext()) {
String[] kv = (String[]) itss.next();
out.println(kv[0]+"="+kv[1]);
}
}
out.close();
}
// Simple test:
public static void main(String[] args) throws Exception {
String path = "c://Action.ini";
IniFile pro = new IniFile(path);
System.out.println(pro);
pro.setValue("N66","in","-in");
pro.save();
pro = null;
}
}