String webPath = request.getServletPath();
log.info(webPath);
输出:
/zjdlbb/zjdlbb/zjdlbb/test.ht
log.info(request.getServletContext().getRealPath("/"));
输出:
E:Program Files (x86)workspaceomsweb
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:Programworkspacefreemarker
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");//关键啊 !