A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张森 中级黑马   /  2013-1-5 17:42  /  1476 人查看  /  2 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张向辉 于 2013-1-16 11:30 编辑

两种常见的方式 ,第一种是利用ResourceBundle,较为方便,一个是利用类加载器

/**
* 获取properties配置文件中的内容方法:
*/
public class ReadProperties {
        // 方法一
        public void One() {
                ResourceBundle bundle = ResourceBundle.getBundle("test");// 获得资源包
                Enumeration<String> allName = bundle.getKeys();// 通过资源包拿到所有的名称
                // 遍历
                while (allName.hasMoreElements()) {
                        String name = (String) allName.nextElement();// 获取每一个名称
                        String value = bundle.getString(name);// 利用已得到的名称通过资源包获得相应的值
                        System.out.println(name + "=" + value);
                }
        }

        // 方法二
        public void Two() throws Exception {
                InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("test.properties");// 获得类加载器,然后把文件作为一个流获取
                Properties prop = new Properties();
                prop.load(in);// 将Properties和流关联
                Enumeration<?> allName = prop.propertyNames();// 获取所有的名称
                while (allName.hasMoreElements()) {
                        String name = (String) allName.nextElement();// 获得每一个名称
                        String value = (String) prop.get(name);// 利用已得到的名称通过Properties对象获得相应的值
                        System.out.println(name + "=" + value);
                }
                in.close();
        }
}


评分

参与人数 1技术分 +1 收起 理由
金鑫 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
学习了,受教
回复 使用道具 举报
我说一个可以用传统方法来获取
//properties代码 死代码,可以牢记:
Properties pro = new Properties();
pro.load(in);
pro.getProperty(name);
  1. private void proMethod(InputStream in) throws IOException {
  2.                 Properties pro = new Properties();
  3.                 pro.load(in);
  4.                
  5.                 //获取资源
  6.                 String url = pro.getProperty("url");
  7.                 String username = pro.getProperty("username");
  8.                 String password = pro.getProperty("password");
  9.                 System.out.println("Current read present resource is:");
  10.                 System.out.println(url);
  11.                 System.out.println(username + ":" + password);
  12.         }
复制代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
           String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
           String filename = path.substring(path.lastIndexOf("\\") + 1);/*path.lastIndexOf("\\") return 最后一个\所在的索引  path.substring(path.lastIndexOf("\\"+1) return该字符串索引后的子字符串*/
           System.out.println("获取的文件资源为:" + filename);
           FileInputStream in = new FileInputStream(path);
           proMethod(in);
}

评分

参与人数 1黑马币 +3 收起 理由
张森 + 3 学习了 谢谢

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马