從別人那里看到的代碼,自己再加工整理一下, 除去了一些BUG, 基本上是沒有什么問題, 只是效率上有待改進(jìn). 呵呵
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 項(xiàng)
* @param key 鍵
* @param defaults 默認(rèn)值
* @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 項(xiàng)
* @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);
}
}