package cn.ipanel.ad.framework.util;
import java.io.File;
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.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* 属性文件工具类
* @author lsm
*
*/
public class PropertyUtil {
private final static String fileName = "config.properties";
/**
* 获取config配置文件配置,根据key获取值
* @param key
* @return
*/
public static String getPropertyValue(String key){
try {
File file = new File(CommonUtil.getAbsPathOfProject()+"WEB-INF/classes/config.properties");
FileInputStream fin = new FileInputStream(file);
Properties p = new Properties();
p.load(fin);
String value=p.getProperty(key).trim();
fin.close();
return value;
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据属性关键字读取配置文件中的相关信息
* 如果fileName为null则读取config.properties的配置
* @since
* @param filename 配置文件名
* @param key 属性关键字
* @return
*/
public static String getPropertyValue(String filename,String key){
try {
if(filename == null)
filename = fileName;
Resource resource=new ClassPathResource(filename);
InputStream inputStream =resource.getInputStream();
Properties p = new Properties();
p.load(inputStream);
String value=p.getProperty(key);
inputStream.close();
return value;
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 更改filename属性文件关键字的值
* @param filename
* @param key
* @param value
*/
public static void setPropertyValue(String filename,String key,String value){
Properties prop = new Properties();
try {
Resource resource=new ClassPathResource(filename);
InputStream fis = resource.getInputStream();
prop.load(fis);
File resourceFile=resource.getFile();
String filepath=resourceFile.getPath();
OutputStream fos = new FileOutputStream(filepath);
prop.setProperty(key, value);
prop.store(fos, "Update '" + key + "' value");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取filename配置文件配置,根据key获取值
* @param filename
* @param key
* @return
*/
public static String getPropertyValueNoCache(String filename,String key){
try {
Resource resource=new ClassPathResource(filename);
File file=resource.getFile();
InputStream inputStream=new FileInputStream(file.getAbsolutePath());
Properties p = new Properties();
p.load(inputStream);
String value=p.getProperty(key);
inputStream.close();
return value;
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
作为一个屌丝程序员不得不收藏的工具类 一 基于spring的属性文件工具类
最新推荐文章于 2024-09-21 10:38:43 发布