javaWeb项目下获取当前类的绝对路径
2015-03-09 21:41
405 查看
在开发中我们经常会对文件进行操作,所以也就经常涉及到文件路径问题。那么在JavaWeb项目中如何获取当前项目或Java类的路径呢?
如下代码是一个简单的Servlet 类:
文件都放在这个目录下。
既然得到了以上信息,那么我们如何来读取项目下的一个文件呢?文件所在位置如下:
操作代码如下:
如下代码是一个简单的Servlet 类:
public class First extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 情况1 String realPath = this.getServletContext().getRealPath(""); System.out.println(realPath); // E:\Server\tomcat-6.0.30\webapps\Day003 // 情况2 ClassLoader classLoader = this.getClass().getClassLoader(); String path = classLoader.getResource("").getPath(); System.out.println(path); // /E:/Server/tomcat-6.0.30/webapps/Day003/WEB-INF/classes/ } }由上代码可以得出有两种方法获取当前项目的路径。一是this.getServletContext().getRealPath("");即通过Servlet上下文对象获取路径,该路径指向当前Servlet容器所在位置,也就是当前项目路径;二是通过类加载器获取当前类的路径,在这里特别提醒:所有类的路径都指向 服务器路径/项目名称/WEB-INF/classes/ ,因为项目发布后所有的.class
文件都放在这个目录下。
既然得到了以上信息,那么我们如何来读取项目下的一个文件呢?文件所在位置如下:
操作代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 情况1 // InputStream is = new FileInputStream("1.jpg"); // 报错, java.io.FileNotFoundException: 1.jpg (系统找不到指定的文件。) File file = new File("1.jpg"); System.out.println(file.getAbsolutePath()); // E:\Server\tomcat-6.0.30\bin\1.jpg // 情况2 String realPath = this.getServletContext().getRealPath("1.jpg"); InputStream is2 = new FileInputStream(realPath); // 情况3 ClassLoader classLoader = this.getClass().getClassLoader(); String path = classLoader.getResource("../../1.jpg").getPath(); InputStream is3 = new FileInputStream(realPath); }由上可知,不能使用InputStream is = new FileInputStream("1.jpg"); 因为web项目发布到服务器后文件目录有所改变。所以只能使用上面的情况2,和情况3进行本项目下的文件操作。
相关文章推荐
- JavaScript中获取当前项目的绝对路径
- JavaScript中获取当前项目的绝对路径
- java通过虚拟机设置参数的方式动态获取当前项目的绝对路径
- springmvc获取项目当前绝对路径,进行下载文件
- JavaWeb的Filter中获取当前项目物理路径
- 使用spring获取项目的绝对路径,就算打JAR包一样获得当前项目的绝对路径
- 在JAVA web中获取该项目的相对路径和绝对路径
- 获取当前进程的绝对路径
- 获取各类项目的当前路径
- C#、ASP.NET获取当前应用程序的绝对路径,获取程序工作路径
- JSP中获取当前绝对路径 获取用户IP地址
- Ruby中获取当前脚本的绝对路径
- 在JSP中获取当前文件,当前文件夹,当前web的绝对路径
- PHP 获取当前文件夹的绝对路径
- windows linux 下,获取java项目绝对路径的方法
- 获取项目各种路径 类:classpath目录的绝对路径,request取得路径
- php dirname(__FILE__) 获取当前文件的绝对路径
- JSP中获取当前绝对路径
- 获取当前SWF文件的绝对路径
- C#、ASP.NET获取当前应用程序的绝对路径,获取程序工作路径