Java.util.Properties工具类
作用:对属性文件的简单读写
在项目中用到了很对时间的对比,但是我又不想把它写死,所以一直在找一种比较简洁的使用配置文件来代替代码中的参数,好了,上代码了。
package cn.com.plustv.utils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import cn.com.plustv.InteractionCode;
public class PropertiesUtils {
private static Properties properties=new Properties();
private static Logger logger = Logger.getLogger(PropertiesUtils.class); //log4j日志输出的方法
static{
try {
InputStream fis = new FileInputStream(System.getProperty("user.dir") +"/conf/env.properties");
//注意属性配置文件所在的路径 ,因为我的程序要打jar包,所以我在项目下建立了conf文件夹,此文件夹和src同级,故需要System.getProperty("user.dir")来进行拼接。
//如果你的项目不需要,直接采用properties.load(PropertiesUtils.class.getClassLoader().getResourceAsStream("./properties/env.properties")); 就可以了,而
properties.load(fis);
} catch (Exception e) {
logger.error(e.getMessage()); //此处是我项目中采用dom4j来进行日志输出
}
}
//读取属性配置文件中的某个属性对应的值
public static String readProperty(String property){
return (String) properties.get(property);
}
}
上面是PropertiesUtils类,我自己放在一个工具包中,如下图所示:
下面是env.properties文件的内容,如下图所示:
因为在项目中我需要的int值,所以需要进行以下转换
package cn.com.plustv.utils;
public class Test {
private static int uploadTime;
private static int onlineTime;
private static int offlineTime;
private static int TimerTime;
private static int timeinterval;
static {
String imageupload1 = "imageupload";
String onlineimage1 = "onlineimage";
String offlineimage1 = "offlineimage";
String timer = "timer";
String timeintervalStr = "timeinterval";
String uploadValue = PropertiesUtils.readProperty(imageupload1);
String onlineValue = PropertiesUtils.readProperty(onlineimage1);
String offlineValue = PropertiesUtils.readProperty(offlineimage1);
String timertimer = PropertiesUtils.readProperty(timer);
String timeintervalValue = PropertiesUtils.readProperty(timeintervalStr);
uploadTime = Integer.parseInt(uploadValue);//在此时我进行了转换
onlineTime = Integer.parseInt(onlineValue);
offlineTime = Integer.parseInt(offlineValue);
TimerTime = Integer.parseInt(timertimer);
timeinterval = Integer.parseInt(timeintervalValue);
}
public static void main(String[] args) {
System.out.println("imageupload的时间是"+uploadTime);
System.out.println("onlineimage的时间是"+onlineTime);
System.out.println("offlineimage的时间是"+offlineTime);
System.out.println("timer的时间是"+TimerTime);
System.out.println("timeinterval的时间是"+timeinterval);
}
}
最后运行得到以下结果: