如何在运行时获取Java应用程序的真实路径?

Sam*_*hra 36 java filepath

我正在创建一个Java应用程序,我正在使用log4j.我已经给出了配置log4j文件的绝对路径以及生成的日志文件的绝对路径(生成此日志文件的位置).我可以在运行时通过以下方式获取Java Web应用程序的绝对路径:

String prefix =  getServletContext().getRealPath("/");
Run Code Online (Sandbox Code Playgroud)

但在普通Java应用程序的上下文中,我们可以使用什么?

Qwe*_*rky 48

尝试;

String path = new File(".").getCanonicalPath();
Run Code Online (Sandbox Code Playgroud)

  • 还有`System.getProperty("user.dir")`,它不能抛出`IOException`. (15认同)
  • 这是否真的返回安装应用程序的目录?它看起来应该返回工作目录,这不一定是同一件事. (6认同)
  • 经过测试,它返回工作目录,而不是应用程序的目录。 (2认同)

use*_*421 30

目前尚不清楚你的要求是什么.我不知道'对于我们正在使用的Web应用程序' getServletContext().getRealPath()是什么意思,如果不是答案,但是:

  • 当前用户的当前工作目录由 System.getProperty("user.dir")
  • 当前用户的主目录由 System.getProperty("user.home")
  • 从中加载当前类的JAR文件的位置this.getClass().getProtectionDomain().getCodeSource().getLocation().

  • @Gary你在发布之前看过文档了吗?它是当前的工作目录.`user.home`是用户的主目录. (2认同)

小智 9

那么使用this.getClass().getProtectionDomain().getCodeSource().getLocation()呢?


Bul*_*aza 7

由于 a 的应用程序路径JAR和从 an 内部运行的应用程序路径IDE不同,我编写了以下代码以始终返回正确的当前目录:

import java.io.File;
import java.net.URISyntaxException;

public class ProgramDirectoryUtilities
{
    private static String getJarName()
    {
        return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .getPath())
                .getName();
    }

    private static boolean runningFromJAR()
    {
        String jarName = getJarName();
        return jarName.contains(".jar");
    }

    public static String getProgramDirectory()
    {
        if (runningFromJAR())
        {
            return getCurrentJARDirectory();
        } else
        {
            return getCurrentProjectDirectory();
        }
    }

    private static String getCurrentProjectDirectory()
    {
        return new File("").getAbsolutePath();
    }

    private static String getCurrentJARDirectory()
    {
        try
        {
            return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
        } catch (URISyntaxException exception)
        {
            exception.printStackTrace();
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

只需打电话getProgramDirectory(),无论哪种方式都应该很好。