打赏

web项目中从不同的路径读取文件

项目中的配置文件可以放在classpath下,webapp下获取其他任何一个指定的绝对地址,读取这些文件就从这三个地方去找。主要代码如下:

 1  private List<String> getPathList(String filePaht){
 2        List<String> list = new ArrayList<String>();
 3        String realPaht = "";
 4        //获取classpath路径
 5        realPaht = UserPrivServiceImpl.class.getResource("/").getPath()+ filePaht;
 6        list.add(realPaht);
 7        //获取webapp路径
 8        realPaht = servletContext.getRealPath("/") + filePaht;
 9        list.add(realPaht);
10        //获取绝对路径
11        list.add(filePaht);
12        return list;
13    }
14 
15 
16 private void initPolicy(){
17        List<String> policyPaht = getPathList(policyFile);
18        if(policyPaht != null && policyPaht.size() > 0 ){
19            for(String path : policyPaht){
20                try{
21                    initPolicy(path);
22                    logger.info("从路径:["+path+"]找到文件policy.yml,加载成功。");
23                    break;
24                }catch (FileNotFoundException e) {
25                       logger.info("从路径:["+path+"]中没找到文件policy.yml,尝试从其他加载方式。");
26                } catch (UnsupportedEncodingException e) {
27                     e.printStackTrace();
28               }
29            }
30        }
31    }

参数中的filePath是在配置文件中配置的policy.yml文件路径。

servletContext是在spring环境中自动注入的
@Autowired
private ServletContext servletContext;

 

posted @ 2016-01-14 17:08  矮子爬楼梯  阅读(411)  评论(0编辑  收藏  举报