注意:
a、以下这些通过方法取得的路径字符串结尾都没有“/”
b、在进行路径字符串拼接时候,为避免分隔符漏写,要习惯开头和结尾都加上分隔符,程序运行时会自动合并分隔符重复
request.getRealPath("/")+"/test\\"
c、读取Windows下的路径只能使用“\”
d、在linux下只能使用"/"
e、在拼接字符串时可以用File.separator代替斜杠,在跨平台使用时不用去注意斜杠写法,或者都使用"/"
File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
f、java中“/”与“\\”是一样的
1、jsp中获取
request.getRequestURI()
结果:/TEST/test.jsp
request.getContextPath()
结果::/TEST
request.getServletPath()
结果: /TEST/jsp/test.jsp
application.getRealPath(“页面.jsp”)
结果:D:\tomcat\webapps\TEST\test.jsp
absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
结果:D:\tomcat\webapps\TEST
2、类中获取
(1).Test.class.getResource(“”)
得到的是当前类FileTest.class文件的URI目录。不包括自己!
(2).Test.class.getResource(“/”)
得到的是当前的classpath的绝对URI路径。
(3).Thread.currentThread().getContextClassLoader().getResource(“”)
得到的也是当前ClassPath的绝对URI路径。
(4).Test.class.getClassLoader().getResource(“”)
得到的也是当前ClassPath的绝对URI路径。
(5).ClassLoader.getSystemResource(“”)
得到的也是当前ClassPath的绝对URI路径。
(6) new File(“”).getAbsolutePath()也可用。
3、servlet中获取
request.getScheme() //输出:http
request.getServerName() //输出: localhost
request.getServerPort() //输出: 8080
request.getContextPath() //输出: /demo
request.getRequestPath() //输出: /Index.jsp
request.gerRequestURI() //输出: /demo/Index.jsp
request.getRequestURL() //IE输出: http://localhost:8080/demo/Index.jsp
request.getRealPath("") //输出:D:\apache-tomcat-6.0.10\webapps\demo
不建议使用request.getRealPath(“/”);
通常使用request.getSession().getServletContext().getRealPath("/");
request.getSession().getServletContext()其实取到的是application