如本地存放文件:ad.properties
里面的内容为:lev1=001,002,003,004,
lev2=005,007,
lev3=002,003
新建java类 JProperties.java
package com.bjsoft.util;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;
/**
* 该类主要作用为读取本地propertie文件
* @author Administrator
*/
public class JProperties {
private static final Logger logger = Logger.getLogger(JProperties.class);
private Properties propertie;
private FileInputStream inputFile;
/**
* 初始化JProperties 类
*/
public JProperties(){
propertie = new Properties();
}
/**
* 初始化JProperties 类
* 加载本地文件
* @param filePath 文件存储路径
*/
public JProperties(String filePath){
propertie = new Properties();
try{
inputFile = new FileInputStream(filePath);
propertie.load(inputFile);
inputFile.close();
}catch (Exception e) {
// TODO: handle exception
logger.info("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
e.printStackTrace();
}
}
/**
* 返回要获取的值
* @return key
*/
public String getValue(String key){
if(propertie.containsKey(key)){
String value = propertie.getProperty(key); //得到某属性的值
return value;
}else{
return "";
}
}
/**
* 重载函数 得到key的值 value
* @param fileName propertie文件的路径+文件名
* @param key 得到其值的键
* @return value key的值
*/
public String getValue(String fileName, String key){
try{
String value = "";
inputFile = new FileInputStream(fileName);
propertie.load(inputFile);
inputFile.close();
if(propertie.containsKey(key)){
value = propertie.getProperty(key);
return value;
}else{
return "";
}
}catch (Exception e) {
logger.info("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在");
e.printStackTrace();
return "";
}
}
/**
* 清除propertie文件所有的key值
*/
public void clear(){
propertie.clear();
}
}
测试运行效果:TestJP.java
package com.bjsoft.util;
import java.util.ArrayList;
public class TestJP {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JProperties jp = new JProperties("D:\\java\\webapps\\ip\\ipv6\\ad.properties");
String ad1 = jp.getValue("lev1");
String ad2 = jp.getValue("lev2");
System.out.println("广告1的值:"+ad1+",广告的长度:"+ad1.length());
System.out.println("广告2的值:"+ad2+",广告的长度:"+ad2.length());
}
}