JavaWeb中获取资源文件路径

来源:互联网 发布:js.users.51.la 编辑:程序博客网 时间:2024/06/05 17:19
文件名  项目路径    服务器路径                 获取方案1.txt  src        /day09/web-inf/classes     02342.txt  /          /day09                       03.txt  /web-inf   /day09/web-inf               04.txt  /src/cn..  /day09/web-inf/classes/cn... 01234 首选1

这里写图片描述
要想获取以上文件路径该怎么办呢?

package cn.itcast.g_path;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ClasspathServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        String path1 = ClasspathServlet.class.getResource("").getPath();        String path2 = ClasspathServlet.class.getResource("/").getPath();        String path3 = ClasspathServlet.class.getClassLoader().getResource("").getPath();        String path4 = ClasspathServlet.class.getClassLoader().getResource("/").getPath();        ServletContext context=this.getServletContext();        String path0=context.getRealPath("/");          System.out.println(path0);        System.out.println(path1);        System.out.println(path2);        System.out.println(path3);        System.out.println(path4);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {    }}

结果为:

E:\apache-tomcat-7.0.69\webapps\day09\/E:/apache-tomcat-7.0.69/webapps/day09/WEB-INF/classes/cn/itcast/g_path//E:/apache-tomcat-7.0.69/webapps/day09/WEB-INF/classes//E:/apache-tomcat-7.0.69/webapps/day09/WEB-INF/classes//E:/apache-tomcat-7.0.69/webapps/day09/WEB-INF/classes/
0 0
原创粉丝点击