一文搞懂Java中相对路径与绝对路径
- 在java中路径分隔使用正斜杠 /,不推荐使用反斜杠\(因为反斜杠需要转义两个反斜杠表示一个正斜杠)。
- 在windows磁盘中用**反斜杠/**表示路径的分隔
- 在浏览器中用**正斜杠/**来表示路径的分隔
- 绝对路径在字符串中写全即可以下主要探讨相对路径的使用
以下java代码都用正斜杠表示斜杠
1、Java中
-
如果路径开头是斜杠以java项目所在的磁盘为起始路径
File file1 = new File("/");
System.out.println("file1 的绝对路径为:" + file1.getAbsolutePath());
File file2 = new File("/new.txt");
System.out.println("file2 的绝对路径为:" + file2.getAbsolutePath());
-
直接以文件名开头
File file2 = new File("new.txt");
System.out.println("file2 的绝对路径为:" + file2.getAbsolutePath());
-
如上可看到以直接文件名开头java的相对路径是以java所在项目的为起始点
-
在java中不存在./表示当前目录,…/表示上一级目录,如果输入…/java程序会把…当作文件夹名
File file2 = new File("../new.txt");
System.out.println("file2 的绝对路径为:" + file2.getAbsolutePath());
- 上图可以看到java程序并没有返回上一级目录创建文件 而是把…当作了一个文件夹以此验证了上面的结论。
2、Servlet中
- 如果路径开头是斜杠以java项目所在的磁盘为起始路径 这个和java中一样
File file1 = new File("/");
resp.getWriter().println(file1.getAbsolutePath());
File file2 = new File("/new.txt");
resp.getWriter().println(file2.getAbsolutePath());
-
直接以文件名开头
File file2 = new File("new.txt");
resp.getWriter().println(file2.getAbsolutePath());
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A856EDpL-1674112520637)(https://picture05.oss-cn-beijing.aliyuncs.com/Path/5.png)]
-
演示this.getServletContext().getResource()返回路径
URL resource = this.getServletContext().getResource("/WEB-INF/classes/db.properties");
resp.getWriter().println(resource.getPath());
/WEB-INF/classes/db.properties 第一个/可有可无
- this.getServletContext().getResource返回的路径是D:/tomcat-8.5/webapps/c3
- webapps是存放web项目的 c3是当前web项目的虚拟映射路径
3.案例
Properties properties = new Properties();
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
properties.load(is);
String name = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().println("name="+name);
resp.getWriter().println("pwd="+pwd);
为什么this.getServletContext().getResourceAsStream(“/WEB-INF/classes/db.properties”);这样读取?
- 请求转发
- 请求转发是服务器内部操作,路径只带要转发的路径即可。
- 重定向
- 重定向是浏览器的两次请求或多次请求,可以放问跨web资源,所以写路径要带上Tomcat的虚拟映射路径+转发的路径
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)