zoukankan      html  css  js  c++  java
  • 获取web项目根目录下的文件,读取web项目根目录下的某个文件

    方法一:

    String path =  this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    path = path.substring(0,path.indexOf("/WEB-INF"));
    String fileName =path+"/xxx.txt";
    方法二:
    这个就比较简单了,直接看代码:
    BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/4_4.xml"),"utf-8"));
    String s = "";
    StringBuffer sb = new StringBuffer("");
    while ((s = br.readLine()) != null) {
        sb.append(s + " ");
    }
    br.close();

    方法三:

    inStream=DaoFactory.class.getClassLoader().getResourceAsStream("com/jdbc/dao/dao.properties");

    第三种是最本质的做法,前两种也是基于第三种去实现的。JVM会使用Bootstrap Loader去加载资源文件。所以路径还是这种相对于工程的根目录即"com/jdbc/dao/dao.properties"(不需要“/)

    InputStream inStream = DaoFactory.class.getResourceAsStream("dao.properties"); --采用的相对路径

    inStream=DaoFactory.class.getResourceAsStream("/com/jdbc/dao/dao.properties") --采用绝对路径,绝对路径是相对于classpath根目录的路径

  • 相关阅读:
    TCP/IP三次握手四次挥手
    注解(JDK1.5之后)
    枚举(JDK1.5之后)
    局部内部类
    非静态内部类
    静态内部类
    匿名内部类
    接口
    根父类:java.lang.Object
    native关键字
  • 原文地址:https://www.cnblogs.com/godfrey/p/7792968.html
Copyright © 2011-2022 走看看