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);
}
}
读写属性文件
最新推荐文章于 2020-05-19 22:38:54 发布