文件读取工具类读取properties文件

1、创建工具类

import java.io.IOException;

import java.util.Properties;



/**

 * 

* 类名称:PropertiesUtil   

* 类描述: 文件读取类

* 创建人:Jxufe HeHaiYang

* 创建时间:2015-1-20 下午03:14:02     

* 修改备注:   

* @version

 */

public class PropertiesUtil {    



    private static Properties properties=new Properties();

    

    private static PropertiesUtil propertiesUtil;

    

    private PropertiesUtil(){        

    }

    

    private static void loadFile(String filename){

        try {

            properties.load(PropertiesUtil.class.getResourceAsStream("/"+filename));

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    

    public static synchronized PropertiesUtil createPropertiesUtil(String filename){

        if (propertiesUtil==null) {

            propertiesUtil=new PropertiesUtil();

        }

        loadFile(filename);

        return propertiesUtil;

    }    

    

    public String getProperty(String key){

        return properties.getProperty(key);

    }



    public static void main(String[] args) {

        PropertiesUtil propertiesUtil=PropertiesUtil.createPropertiesUtil("upload.properties");        

        System.out.println(propertiesUtil.getProperty("path"));

    }

}
PropertiesUtil.java

2、使用全局变量

/**

 * 

* 类名称:Constant   

* 类描述: 全局静态变量

* 创建人:Jxufe HeHaiYang

* 创建时间:2015-1-21 下午01:53:47     

* 修改备注:   

* @version

 */

public class Constant {



    public static final String UPLOADPATH_FILE="upload.properties";

    

    public static final String UPLOADPATH_PATH="path";

    

}

3、调用工具类

读取定义的upload.properties文件

    PropertiesUtil pUtil = PropertiesUtil

        .createPropertiesUtil(Constant.UPLOADPATH_FILE);

取出定义的path的值

        pUtil.getProperty(Constant.UPLOADPATH_PATH);

 

你可能感兴趣的:(properties)