项长老

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

类装载器

public class userDAO {
    
    private static Properties dbconfig =new Properties();
    
    static{
        try {
              InputStream instream =userDAO.class.getClassLoader().getResourceAsStream("db.propertites");
              dbconfig.load(instream);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public void update() throws IOException {        
      System.out.println(dbconfig.getProperty("url"));        
    }
    
    public void find() throws IOException {        
             
        }
    
    public void delete() throws IOException {        
            
        }

}

  

使用类装载器读取文件的弊端:

1.文件不能太大,因为它是以装载类的方式一次性加入内存中

2.类装载器只会加载一次,就是说不能显示文件的更新操作

 

如果需要读到实时数据,就不能通过类装载器来读文件,需要通过普通的文件路径的方式

public class DAO {
    
    public void update() throws IOException{
      
        String path = DAO.class.getClassLoader().getResource("db.properties").getPath();
        FileInputStream in= new FileInputStream(path);
        
        Properties pros = new Properties();
        pros.load(in);
        
        String url = pros.getProperty("url");    

    }

}

  

 

参考资料:

http://www.cnblogs.com/tech-bird/p/3843832.html

posted on 2016-02-12 17:16  项长老  阅读(256)  评论(0编辑  收藏  举报