Java获取程序或项目路径的常用方法

qsuron 发布于 2014-02-23 Java 36 次阅读 无~ 366 字 预计阅读时间: 2 分钟


在我们写java程序的时候,不可避免地会需要获取当前文件或者是当前程序的的绝对路径

比较常用的方法有:

1 普通环境下 在任意的class里调用:

//获取绝对路径
this.getClass().getClassLoader().getResource("/").getPath();

这个方法也可以不在web环境里确定路径,比较好用

2 WEB环境下 在servlet的init方法里

String path = getServletContext().getRealPath("/");
//这将获取web项目的全路径
//例如 :E:eclipseM9workspacetree
//tree是我web项目的根目录

3.获得web根的上下文环境

request.getContextPath();
//如 /tree 是我的web项目的root context
/*jsp 取得当前目录的路径*/
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/*/
path=C:jboss-4.0.5.GAserverdefaulttmpdeploytmp14544test-exp.war
String   path   =   (String)request.getContextPath();
/*得到项目(test)应用所在的真实的路径 path=/test*/
String     path     =   request.getRequestURI();
/*得到应用所在的真实的路径 path=/test/admin/admindex.jsp*/
String   savePath=request.getRealPath(request.getServletPath());
/*得到当前文件的磁盘绝对路径*/
//JAVA 取得当前目录的路径
File   file=new   File(".");
String path=file.getAbsolutePath();
                path=file.getPath();
/*得到jboss运行目录 path=C:jboss-4.0.5.GAbin*/

4.获取jar包源路径/java文件源路径,支持中文目录!

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Ini extends JFrame{
    private static String LOCATION;
    static {
        try {
            LOCATION = URLDecoder.decode(Ini.class.getProtectionDomain().getCodeSource().getLocation().getFile(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOCATION = "";
        }
    }
    public static void main(String[] args) throws IOException {
        System.out.println(LOCATION);
    }
}  
代码敲的累了,换个中文悠闲悠闲。
最后更新于 2014-02-23