从别人那里看到的代码,自己再加工整理一下, 除去了一些BUG, 基本上是没有什么问题, 只是效率上有待改进. 呵呵
package com.yhuhu.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FileUtil {
/**
* 读取INI配置
* @param file INI配置文件完整路径
* @param sec 项
* @param key 键
* @param defaults 默认值
* @return
*/
@SuppressWarnings("unchecked")
public static String GetPrivateProfileString(String file,String sec,String key,String defaults)
{
String result = defaults;
Map map = getIniAllValue(file);
if(map==null)
return result;
ArrayList section = (ArrayList)map.get(sec);
if(section!=null)
{
Iterator iter = section.iterator();
while(iter.hasNext()){
String[] kv = (String[])iter.next();
if(kv!=null && kv[0].equals(key.trim())){
return dealCorpsSign(kv[1],2);
}
}
}
return defaults;
}
/**
* 写入配置 INI文件
* @param file INI配置文件完整路径
* @param sec 项
* @param key 键
* @param value 值
* @return
*/
@SuppressWarnings("unchecked")
public static boolean WritePrivateProfileString(String file,String sec,String key,String value)
{
value = dealCorpsSign(value,1);
Map map = getIniAllValue(file);
if(map==null)
{
map = new HashMap();
ArrayList section = new ArrayList();
section.add(new String[]{key,value});
map.put(sec, section);
}
else {
int x = 0,y = 0;
ArrayList al = (ArrayList)map.get(sec);
if(al!=null){
Iterator iter = al.iterator();
while(iter.hasNext()){
x++;
String[] kv = (String[])iter.next();
if(kv!=null && kv[0].equals(key)){
kv[1] = value;
y++;
}
}
}
if(x==0){
ArrayList section = new ArrayList();
section.add(new String[]{key,value});
map.put(sec, section);
}
else if(y==0){
al.add(new String[]{key,value});
map.put(sec, al);
}
}