import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PropertiesUtil {
private static Log logger=LogFactory.getLog(PropertiesUtil.class);
/**
* 从指定配置文件中读取指定key对应的value
* @param path
* @param key
* @return
*/
public static String readDefProperties(String path,String key){
String value = "";
Properties pro=new Properties();
FileInputStream fis=null;
try {
fis = new FileInputStream(path);
BufferedReader bf = new BufferedReader(new InputStreamReader(fis));
pro.load(bf);
value = (String) pro.get(key);
} catch (FileNotFoundException e) {
logger.error("指定配置文件"+path+"不存在...", e);
value = "";
} catch (IOException e) {
logger.error("指定配置文件"+path+"读取异常...", e);
value = "";
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
fis=null;
}
}
}
return value;
}
/**
* 更新指定配置文件中指定的key对应的value
* @param path
* @param key
* @param value
*/
public static void writePropertiesFile(String path,String key,String value)
{
Properties properties = new Properties();
try
{
FileInputStream fis=null;
fis = new FileInputStream(path);
BufferedReader bf = new BufferedReader(new InputStreamReader(fis));
properties.load(bf);
OutputStream outputStream = new FileOutputStream(path);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
properties.setProperty(key,value);
properties.store(bw, "Update '" + key + "' value");
outputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(PropertiesUtil.readDefProperties("./config/controlProg.properties", "ocxs"));
PropertiesUtil.writePropertiesFile("./config/controlProg.properties", "ocxs", "影像扫描控件,影像查看控件");
}
}
Eclipse中properties文件读取时中文乱码、指定更新、写入中文变unicode码的解决方法
最新推荐文章于 2022-11-11 14:24:32 发布