读书人

动态定位jar包途径以及读取配置文件

发布时间: 2012-08-28 12:37:01 作者: rapoo

动态定位jar包路径,以及读取配置文件信息
因为要做一个定时器,按照特定频率去访问url,写完代码需要打包给其他人执行测试:遇到了关于路径的问题,解决了好几天各种百度才弄好。

直接上代码:

//得到文件路径,其实得到的是:项目项目的bin目录(我在Eclipse环境下,如果你没看到bin目录,就把视图从package explorer模式切换到project explorer)[color=red]String path = DatabaseProperty.class.getProtectionDomain().getCodeSource().getLocation().getFile();  [/color]try {//转换格式,处理中文和空格path = java.net.URLDecoder.decode(path, "UTF-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}//得到该文件的父目录,也就是我希望把配置文件database.properties和jar文件放在同级目录,方便三方用户修改。String filePath = (new File(path)).getParentFile().getAbsolutePath()+"\\database.properties";//读取配置文件Properties pro = new Properties();try {InputStream ips = new BufferedInputStream(new FileInputStream(filePath));pro.load(ips);String value = pro.getProperty(key);return value;} catch (Exception e) {e.printStackTrace();return null;}

读书人网 >编程

热点推荐