在我们的代码中,经常需要将一些值放到配置文件中读取,这样的好处就是可以不需要重新编译代码就可以改变一些系统的属性,今天分享一个用java 读取properties配置文件的方法。
我把它直接写成了一个工具类,我现在每个项目开始之前,总要将这个工具类先放进去,具体方法是:可以直接将这个工具类放入util 包中就可以的使用里面的方法实现读取和写配置的功能了!
下面直接上代码
package com.proven.util;
import java.io.BufferedInputStream;
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.util.Date;
import java.util.Properties;
/**
*
* @ClassName: PropertyUtil
* @author weilong
* @date 2019年5月14日
*/
public class PropertyUtil {
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
props = new Properties();
InputStream inputStream=null;
try {
inputStream = new BufferedInputStream(new FileInputStream(new File("config/config.properties")));
props.load(inputStream);
} catch (FileNotFoundException e) {
System.out.println("config.properties文件未找到");
} catch (IOException e) {
System.out.println("出现IOException");
} finally {
try {
if(null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
System.out.println("config.properties文件流关闭出现异常");
}
}
System.out.println("加载properties文件内容完成...........");
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
public static void setProperty(String key,String value) {
try {
if(null == props) {
loadProps();
}
FileOutputStream oFile = new FileOutputStream(new File("config/config.properties"));
props.setProperty(key, value);
props.store(oFile, new Date().toString());
oFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用方法:PropertyUtil.getProperty(key),PropertyUtil.setProperty(key,value)
其中getProperty 方法是从配置文件中读取配置。setProperty方法是从把值写进配置文件中去。
其中项目的目录是这样的
希望对读者开发有帮助!