propertiesプロファイル読み書き操作ツールクラス
3463 ワード
JAvaのpropertiesプロファイルに対する読み書き操作ツールクラス:
コードは次のとおりです.
この例では、propertiesプロファイルはclasspathの下のconfディレクトリに配置する必要があり、idというkeyが含まれています.
コードは次のとおりです.
package com.syxp.moa.message.weiguiwailian.common;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* properties
* @author
*
*/
public class ReadWriteTools {
//
private static String propertiesPath ;
private static Logger logger = Logger.getLogger(ReadWriteTools.class);
static {
//
propertiesPath=System.getProperty("user.dir")+"/conf/weiguilianjie.properties";
}
/**
* key value
* @param key:
* @param filePath:
*/
public static String readValue(String propertiesPath,String key){
Properties properties = new Properties();
try{
InputStream is = new BufferedInputStream(new FileInputStream(propertiesPath));
properties.load(is);
String value = properties.getProperty(key);
is.close();
return value;
}catch(Exception e){
logger.error(" !",e);
return null;
}
}
/**
* key value
* @param key:
*/
public static String readValue(String key){
Properties properties = new Properties();
try{
InputStream is = new BufferedInputStream(new FileInputStream(propertiesPath));
properties.load(is);
String value = properties.getProperty(key);
is.close();
return value;
}catch(Exception e){
logger.error(" !",e);
return null;
}
}
/**
* ( ) properties ( )
* , ;
* , 。
* @param keyName:
* @param keyValue:
*/
public static void writeProperties(String keyName,String keyValue){
try{
// HashTable put, getProperty 。
// 。 HashTable put 。
//
Properties properties = new Properties();
properties.load(new FileInputStream(propertiesPath));
OutputStream os = new FileOutputStream(propertiesPath);
properties.setProperty(keyName, keyValue);
// load Properties ,
// Properties ( )
properties.store(os, "Update '" + keyName + "' value");
os.close();
}catch(FileNotFoundException e){
logger.error(" !",e);
}catch(IOException e){
logger.error(" ",e);
}finally{
}
}
//
public static void main(String[] args) {
System.out.println("readValue==" + readValue("id"));
writeProperties("id", "5");
System.out.println("readValue==" + readValue("id"));
System.out.println(" !");
}
}
この例では、propertiesプロファイルはclasspathの下のconfディレクトリに配置する必要があり、idというkeyが含まれています.