Java讀取配置文件

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by zhangyue on 16/9/22.
 * 讀取配置文件工具類
 */
public class PropertiesUtil {

    private static String username;
    private static String password;
    private static String url;
    private static String slaveUrl;
    private static String driver;

    public void init(){
        InputStream is=null;
        try {
             is = this.getClass().getClassLoader().getResourceAsStream("app.properties");
            System.out.println("is:"+is);
            Properties properties = new Properties();
            properties.load(is);
            //中文可能會出現亂碼,須要轉換一下
            username = new String(properties.getProperty("username").getBytes("ISO-8859-1"), "UTF-8");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            slaveUrl = properties.getProperty("slaveUrl");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    public String toString() {
        return "PropertiesUtil{} \n"+PropertiesUtil.username+",\n"+PropertiesUtil.password
                +",\n"+PropertiesUtil.url+",\n"+PropertiesUtil.slaveUrl
                +",\n"+PropertiesUtil.driver;
    }


    public static String getValueByProperiesKey(String key){
        InputStream is=null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream("app.properties");
            System.out.println("is:"+is);
            Properties properties = new Properties();
            properties.load(is);
            password = properties.getProperty(key);
            return password;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";

    }

    public static void main(String[] args) {
        PropertiesUtil p = new PropertiesUtil();
        p.init();
        System.out.println(p.toString());

        System.out.println(PropertiesUtil.getValueByProperiesKey("maxActive"));
    }


}
相關文章
相關標籤/搜索