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")); }}