路径问题整理
Write By CS逍遥剑仙
我的主页: csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: sunjianfeng@csxiaoyao.com
QQ: 1724338257
1 "/" 的区别
1.1 服务器端和客户浏览器端
服务器 / 表示在webRoot的根目录下(不需要带项目名)
浏览器 / 表示在webapps的根目录下(需要写项目名)
1.2 应用实例
转发
request.getRequestDispatcher("/target.html").forward(request, response);
请求重定向
response.sendRedirect("/project/target.html");
html页面超连接
response.getWritcsxiaoyao.com er().write("<html><body><a href='/project/target.html'>超链接</a></body></html>");
html页面中的form提交地址
<form action='/project/target.html'>
2 服务器端相对路径读取文件
2.1 "." 定位到tomcat/bin目录下
//错误示例
File("./src/db.properties");
2.2 web应用下加载资源文件的方法
方法一:getRealPath() 读取,返回资源文件的绝对路径
String path = thicsxiaoyao.com s.getServletContext().getRealPath("/WEB-INF/db.properties");
File file = new File(path);
FileInputStream in = new FileInputStream(file);
方法二:getResourceAsStream() 得到资源文件,返回输入流
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
//读取资源文件
Properties prop = new Properties();
prop.load(in);
String user = prop.getProperty("user");
String password = prop.getProperty("password");
3 操作系统区别
3.1 共同点
绝对路径:该文件在硬盘上的完整路径,一般都是以盘符开头的。
相对路径:相对路径就是资源文件相对于当前程序所在的路径。
. 当前路径
.. 上一级路径
3.2 目录分隔符区别
在windows机器上的目录分隔符是 \,在linux机器上的目录分隔符是 /
,在windows上 \ 与 / 都可以使用作为目录分隔符,而且如果写 / 的时候只需要写一个即可
路径示例:
----linux----
/home/sunshine/data.txt
./ 当前目录
../ 上级目录
----windows----
程序中"\"需要写成"\\"
E:\sunshine\a.txt
E:/sunshine/a.txt
E:
../../
System.out.println("目录分隔符:"+ File.separator);
System.out.println("当前路径是:"+ file4.getAbsolutePath());//D:\Workspaces\java_test\.
File parentFile = new File("E:\\");
File file1 = new File("E:"+File.separator+"a.txt");
File file2 = new File("E:/a.txt");
File file3 = new File("E:\\","a.txt");
File file4 = new File(".");
File file5 = new File("..\\..\\a.txt");
4 URI、URL
URI:Uniform Resource Identifier,统一资源标识符
URL:Uniform Resource Locator,统一资源定位符
URL是URI的一个特例,URL能够唯一定位资源
【URI示例】
mailto:cay@horstman.com
【URL示例】
file:///E:/sunshine/a.txt
http://www.csxiaoyao.com/
ftp://home.ustc.edu.cn