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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 吴亨 黑马帝   /  2012-2-9 10:21  /  1620 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 吴亨 于 2012-2-9 20:11 编辑

package com.baidu.exam;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;

public class HashTest {

        public static void main(String[] args) throws Exception
        {
                Point p1 = new Point(1,1);
         Point p2 = new Point(2,2);
         Point p3 = new Point(1,1);
         
         
         InputStream ip = HashSet.class.getResourceAsStream ("configure.properties");
         Properties pro = new Properties();
         pro.load(ip);   //运行时,这句老是出错,出现空指针异常。配置文件和java类在一起。
         ip.close();
         String className = pro.getProperty("className");
         
         Collection collection = (Collection) Class.forName(className).newInstance();
           
         collection.add(p1);
         collection.add(p2);
         collection.add(p3);
         
         System.out.println(collection.size());
        }
}

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

3 个回复

倒序浏览

  1. import java.io.InputStream;
  2. import java.util.Collection;
  3. import java.util.Properties;

  4. public class HashTest {

  5.     public static void main(String[] args) throws Exception {

  6.              InputStream ip = HashTest.class.getClassLoader().getResourceAsStream ("configure.properties");//这样就可以了
  7. //            FileInputStream ip = new FileInputStream("src\\configure.properties");

  8.              Properties pro = new Properties();
  9.              pro.load(ip);   
  10.              ip.close();

  11.              String className = pro.getProperty("className");
  12.              Collection collection = (Collection) Class.forName(className).newInstance();

  13.              collection.add(1);
  14.              collection.add(2);
  15.              collection.add(3);
  16.             
  17.              System.out.println(collection.size());
  18.     }
  19. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
InputStream ip = HashTest.class.getResourceAsStream ("configure.properties");
把conffigure.properties文件放成跟 HashTest同一个包中就可以了。因为如果没有写路径它会默认从当前类所在的包中查找。   
另外 HashTest.class.getClassLoader().getResourceasStream("配置文件");查找配置文件时则是从工程的要目录查找。 要想使用这种方式 直接把配置文件放在src目录下就可以了。。

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
把配置文件放到工程目录下!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马