---
title: "JAVA开发中文件路径汇总"
author: "hujin1979"
date: "2015-03-06T13:41:38Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-03-06T14:19:04Z"
id: 2189349
url: "https://hujin.iteye.com/blog/2189349"
---

1、文件是demo.xml，位置在com.xxx.app包下，你可以用Class.getResourceAsStream("com/xxx/app/demo.xml") 

所有classpath可访问的路径都可以用这种方式

 

2、file.getAbsolutePath()是获取文件当前的绝对路径，如果在Linux下，采取file.getAbsolutePath().replaceAll("\\\\\\\\", "/")后可构造java.net.URL对象：URL url = new URL("file:" + file.getAbsolutePath().replaceAll("\\\\\\\\", "/"))

 

3、想知道class运行的当前目录，可使用System.out.println(new File(".").getAbsolutePath())获得，默认情况下new File（"/"）代表的目录为：System.getProperty（"user.dir"）

 

4、相对路径表示说明：

- FileInputStream fis=new FileInputStream("images/"+id+".jpg")，表示当前运行的.class目录下有一个images目录，里面有特定的jpg图片
- FileInputStream fis=new FileInputStream("../webapps\\\\axis2\\\\WEB-INF/pojo/images/"+id+".jpg")，../表示当前目录的上一级目录
- new FileInputStream("./mysource.properties")，这样写的路径是在当前jar包退出路径下有一个文件名为mysource.properties这样的配置文件
- 在Servlet中，"/"代表Web应用的根目录

5、JSP中获得当前应用的相对路径和绝对路径

- 根目录所对应的绝对路径：request.getRequestURI（）
- 文件的绝对路径  :application.getRealPath（request.getRequestURI（））
- 当前web应用的绝对路径 :application.getRealPath（"/"）
- 取得请求文件的上层目录：new File（application.getRealPath（request.getRequestURI（）））.getParent（）

6、Servlet中获得当前应用的相对路径和绝对路径

- 根目录所对应的绝对路径：request.getServletPath（）；
- 文件的绝对路径request.getSession（）.getServletContext（）.getRealPath（request.getRequestURI（））
- 当前web应用的绝对路径 :servletConfig.getServletContext（）.getRealPath（"/"）

    （ServletContext对象获得几种方式：    

    javax.servlet.（）    

    javax.servlet.jsp.PageContext.getServletContext（）    

    javax.servlet.ServletConfig.getServletContext（）    

    ）

 

测试代码：    

    import java.io.File;

    

    public class FileTest {

    

    public static void main（String\[] args） throws Exception {

    

      System.out.println（Thread.currentThread（）.getContextClassLoader（）.getResource（""））；

    

      System.out.println（FileTest.class.getClassLoader（）.getResource（""））；

    

      System.out.println（ClassLoader.getSystemResource（""））；

    

      System.out.println（FileTest.class.getResource（""））；

    

      System.out.println（FileTest.class.getResource（"/"））； //Class文件所在路径

    

      System.out.println（new File（"/"）.getAbsolutePath（））；

    

      System.out.println（System.getProperty（"user.dir"））；    

     }    

    }

 

获取Java程序运行的路径 | 获取当前jar包的路径

public class MyPath {

 

    public static String getProjectPath() { 

       java.net.URL url = MyPath.class.getProtectionDomain().getCodeSource().getLocation();

 

       String filePath = null;

       try {

           filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");

       } catch (Exception e) {

           e.printStackTrace();

       }

 

       if (filePath.endsWith(".jar"))

          filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);

 

        java.io.File file = new java.io.File(filePath);

        filePath = file.getAbsolutePath();

        return filePath;

  }   

 

    public static String getRealPath() {

        String realPath = MyPath.class.getClassLoader().getResource("").getFile();

        java.io.File file = new java.io.File(realPath);

        realPath = file.getAbsolutePath();

 

        try {

           realPath = java.net.URLDecoder.decode(realPath, "utf-8");

        } catch (Exception e) {

           e.printStackTrace();

       }

       return realPath;

    }   

 

    public static String getAppPath(Class&lt;?&gt; cls){ 

       //检查用户传入的参数是否为空 

        if(cls==null)  

        throw new java.lang.IllegalArgumentException("参数不能为空！");       

 

        ClassLoader loader=cls.getClassLoader(); 

        //获得类的全名，包括包名 

        String clsName=cls.getName();

        //此处简单判定是否是Java基础类库，防止用户传入JDK内置的类库 

        if(clsName.startsWith("java.")||clsName.startsWith("javax.")) {

        throw new java.lang.IllegalArgumentException("不要传送系统类！");

        }

 

        //将类的class文件全名改为路径形式

        String clsPath= clsName.replace(".", "/")+".class";

        //调用ClassLoader的getResource方法，传入包含路径信息的类文件名 

        java.net.URL url =loader.getResource(clsPath); 

        //从URL对象中获取路径信息 

        String realPath=url.getPath(); 

 

        //去掉路径信息中的协议名"file:" 

        int pos=realPath.indexOf("file:"); 

        if(pos&gt;-1) {

        realPath=realPath.substring(pos+5); 

        }

 

        //去掉路径信息最后包含类文件信息的部分，得到类所在的路径 

        pos=realPath.indexOf(clsPath); 

        realPath=realPath.substring(0,pos-1); 

        //如果类文件被打包到JAR等文件中时，去掉对应的JAR等打包文件名 

        if(realPath.endsWith("!")) {

        realPath=realPath.substring(0,realPath.lastIndexOf("/"));

        }

        java.io.File file = new java.io.File(realPath);

        realPath = file.getAbsolutePath();      

 

        try{ 

        realPath=java.net.URLDecoder.decode(realPath,"utf-8"); 

        }catch(Exception e){

        throw new RuntimeException(e);

        } 

        return realPath; 

    }//getAppPath定义结束 

} 

 

使用Jar包，在Tomcat的运行结果如下：

 

ProjectPath: D:\\J2EE\\Tomcat 6.0\\webapps\\MyService1WebP\\WEB-INF\\lib

 

RealPath: D:\\J2EE\\Tomcat 6.0\\webapps\\MyService1WebP\\WEB-INF\\classes

 

Apppath: D:\\J2EE\\Tomcat 6.0\\webapps\\MyService1WebP\\WEB-INF\\classes