zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    ubuntu下安装maven
    159.Longest Substring with At Most Two Distinct Characters
    156.Binary Tree Upside Down
    155.Min Stack
    154.Find Minimum in Rotated Sorted Array II
    153.Find Minimum in Rotated Sorted Array
    152.Maximum Product Subarray
    151.Reverse Words in a String
    150.Evaluate Reverse Polish Notation
    149.Max Points on a Line
  • 原文地址:https://www.cnblogs.com/ahang/p/5130813.html
Copyright © 2011-2022 走看看