package com.jetsum.util;
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;
/**
* 該類用於配置文件的讀寫操作。
* @author ShaoJiang
*
*/
public class PropertiesUtil {
/**
* Properties對象
*/
public static Properties pros = null;
static{
pros = new Properties();
}
/**
* 通過路徑加載配置文件,文件路徑可以是絕對路徑也可以是相對於class文件的路徑。
* @param filePath 文件路徑
*/
public static void load(String filePath){
try {
InputStream in = filePath.contains(":")?new FileInputStream(filePath):PropertiesUtil.class.getResourceAsStream(filePath);
pros.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 從文件加載屬性值
* @param filePath 文件路徑
* @param key 屬性鍵值
* @return 返回屬性值
*/
public static String loadValue(String filePath,String key){
load(filePath);
return get(key);
}
/**
* 獲得配置文件屬性值
* @param key
* @return 返回屬性值
*/
public static String get(String key){
return pros.getProperty(key);
}
/**
* 保存配置文件
* @param filePath 文件路徑
* @param comments 屬性列表的描述
* @return 返回保存成功狀態
*/
public static boolean store(String filePath,String comments){
try {
OutputStream out = new FileOutputStream(filePath.contains(":")?filePath:PropertiesUtil.class.getResource(filePath).getFile());
pros.store(out,comments);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 保存配置文件
* @param filePath 文件路徑
* @return 返回保存成功狀態
*/
public static boolean store(String filePath){
return store(filePath,"update:"+filePath);
}
/**
* 設置配置文件屬性
* @param key 配置key
* @param value 配置value
*/
public static void set(String key,String value){
pros.setProperty(key, value);
}
/**
* 設置配置文件屬性
* @param filePath 文件路徑
* @param key 配置key
* @param value 配置value
* @return 返回保存成功狀態
*/
public static boolean storeValue(String filePath,String key,String value){
load(filePath);
pros.setProperty(key, value);
return store(filePath);
}
/**
* 打印屬性列表
*/
public static void printPropertieList(){
pros.list(System.out);
}
}
讀寫屬性文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.