String webPath = request.getServletPath();
log.info(webPath);
输出:
/zjdlbb/zjdlbb/zjdlbb/test.ht


log.info(request.getServletContext().getRealPath("/"));
输出:
E:\Program Files (x86)\workspace\oms\web\



String webPath = request.getContextPath();
log.info(webPath); 输出:
/oms (项目名) // 使用相对目录的方式读取文件,相对目录即是项目的目录 File file = new File("src" + File.separator + "dom" + File.separator + "xml" + File.separator + "class.xml"); File file2 = new File(DomDemo.class.getClassLoader() .getResource("").getPath().substring(1) + "dom" + File.separator + "xml" + File.separator + "class.xml"); //当前路径 System.out.println(Demo01.class.getResource("."));// file:/D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/demo01/ System.out.println(Demo01.class.getResource(""));// file:/D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/demo01/ System.out.println(Demo01.class.getResource(".").getPath());// /D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/demo01/ System.out.println(Demo01.class.getResource("").getPath());// /D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/demo01/ //根目录 System.out.println(Demo01.class.getResource("/"));// file:/D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ System.out.println(Demo01.class.getResource("/").getPath());// /D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ //项目路径 System.out.println(System.getProperty("user.dir"));// D:\Program\workspace\freemarker System.out.println(Demo01.class.getClassLoader().getResource("."));// file:/D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ System.out.println(Demo01.class.getClassLoader().getResource(""));// file:/D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ System.out.println(Demo01.class.getClassLoader().getResource(".").getPath());// /D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ System.out.println(Demo01.class.getClassLoader().getResource("").getPath());// /D:/Program/workspace/freemarker/WebRoot/WEB-INF/classes/ 注意: 在java中获取文件路径的时候,有时候会获取到空格,但是在中文编码环境下,空格会变成“%20”从而使得路径错误. 解决办法: String path = Parameter.class.getResource("").getPath();//得到路径 path = URLDecoder.decode(path,"utf-8");//关键啊 !

 

相关文章:

  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-12-24
  • 2021-12-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
  • 2022-12-23
  • 2018-03-29
  • 2021-10-07
  • 2021-06-07
相关资源
相似解决方案