java获得路径的多种方式

时间:2023-03-10 03:43:04
java获得路径的多种方式

本文讲解java语言中获得运行时路径的多种方式,包括java项目、java web项目、jar、weblogic等多种场景。

一、this.getClass().getClassLoader().getResource("").getFile()

示例:

String path = this.getClass().getClassLoader().getResource("").getFile();
path = URLDecoder.decode(path,"utf-8");

注意当路径中包含空格、中文等特殊字符时,需要进行转码,否则结果会是这样的:/D:/eclipse%e5%b7%a5%e4%bd%9c%e7%a9%ba%e9%97%b4/Test/bin/

使用这种方式,就不用转码了:

this.getClass().getClassLoader().getResource("").toURI().getPath()

适用场景:

java项目,spring-boot项目源码运行,javaweb项目源码部署到tomcat、weblogic中运行,javaweb项目打包war部署到tomcat运行

不适用场景:

spring-boot项目打包成可执行jar运行,javaweb项目打包war部署到weblogic运行

二、this.getClass().getProtectionDomain().getCodeSource().getLocation()

示例:

private String getBasePath() throws Exception {
        CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource();
        URL location = codeSource == null ? null : codeSource.getLocation();
        File source = null;
        if (location != null) {
            URLConnection connection = location.openConnection();
            if (connection instanceof JarURLConnection) {
                JarFile jarFile = ((JarURLConnection) connection).getJarFile();
                String name = jarFile.getName();
                // name类似于:/xiaoyun-core/target/xiaoyun-core-0.0.1.jar!/BOOT-INF/classes
                int separator = name.indexOf("!/");
                if (separator > 0) {
                    name = name.substring(0, separator);
                }
                source = new File(name);
            } else {
                source = new File(location.toURI().getPath());
            }
        }
        String path = null;
        if (source != null && source.exists()) {
            path = source.getParentFile().getAbsoluteFile().getPath();
        }
        return path;
    }

这种方法是参考spring-boot项目的org.springframework.boot.ApplicationHome写的,当项目以源码方式运行,并且路径中包含中文时,ApplicationHome无法获得路径,所以自己重写了一个。(楚霄云原创文章)

适用场景:

spring-boot项目打包成可执行jar运行,spring-boot项目源码运行,java项目源码运行,java项目打包成可执行jar运行

三、<param-name>webAppRootKey</param-name>

示例:

<context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>xiaoyun.root</param-value>
</context-param>

在javaweb项目的web.xml中添加上边的xml,tomcat启动时就会把项目的根目录添加到系统变量中,项目中任何地方都可以获得,如果项目只在tomcat中运行,推荐这种方式

代码中可以使用System.getProperty("xiaoyun.root")获得

String path = System.getProperty("xiaoyun.root");

log4j.properties、logback.xml、ehcache.xml等配置文件中可以使用${xiaoyun.root}获得

log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.File = ${xiaoyun.root}/logs/error.log

适用场景:

javaweb项目部署到tomcat6及以上版本运行

不适用场景:

java项目,javaweb项目部署到weblogic运行,javaweb项目部署到tomcat5运行

四、event.getServletContext().getRealPath("/")

示例:

public class WebAppRootListener implements ServletContextListener{
    @Override
    public void contextInitialized(ServletContextEvent event) {
        try{
            String rootPath = event.getServletContext().getRealPath("/");
            // tomcat不是null,以源码部署到weblogic时不是null,以war部署到部分weblogic版本时是null
            if(rootPath==null || !new File(rootPath).exists()){
                URL url = event.getServletContext().getResource("/");
                rootPath = url==null?null:url.getFile();
            }
            // 以war部署到部分weblogic版本时是null
            if (rootPath == null || !new File(rootPath).exists()) {
                URL url = this.getClass().getClassLoader().getResource("/");
                if(url!=null){
                    String path = url.getFile();
                    rootPath = path.substring(0, path.length() - 17);
                }
            }
            if (rootPath != null && new File(rootPath).exists()) {
                rootPath = URLDecoder.decode(rootPath, "utf-8"); // 防止路径中出现空格和中文时乱码
                System.setProperty("xiaoyun.root", rootPath);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {}
}

适用场景:

javaweb项目(支持tomcat和weblogic)

不适用场景:

java项目

五、其它

如果只是想读取配置文件的话, 不建议根据文件路径去读取,应该使用this.getClass().getClassLoader().getResourceAsStream("config.xml")