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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4032957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:45:39  来源:igfitidea点击:

How to get the real path of Java application at runtime?

javafilepath

提问by Sameek Mishra

I am creating a Java application where I am using log4j. I have given the absolute path of configuration log4j file and also an absolute path of generated log file(where this log file are generated). I can get the absolute path of a Java web application at run time via:

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

String prefix =  getServletContext().getRealPath("/");

but in the context of a normal Java application, what can we use?

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

采纳答案by Qwerky

Try;

尝试;

String path = new File(".").getCanonicalPath();

回答by Sudantha

If you're talking about a web application, you should use the getRealPathfrom a ServletContextobject.

如果您在谈论 Web 应用程序,则应该使用getRealPathfrom aServletContext对象。

Example:

例子:

public class MyServlet extends Servlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
              throws ServletException, IOException{
         String webAppPath = getServletContext().getRealPath("/");
    }
}

Hope this helps.

希望这可以帮助。

回答by Bozho

new File(".").getAbsolutePath()

回答by user207421

It isn't clear what you're asking for. I don't know what 'with respect to the web application we are using' means if getServletContext().getRealPath()isn't the answer, but:

不清楚你在问什么。如果getServletContext().getRealPath()不是答案,我不知道“关于我们正在使用的 Web 应用程序”是什么意思,但是:

  • The current user's current working directory is given by System.getProperty("user.dir")
  • The current user's home directory is given by System.getProperty("user.home")
  • The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation().
  • 当前用户的当前工作目录由 System.getProperty("user.dir")
  • 当前用户的主目录由 System.getProperty("user.home")
  • 从中加载当前类的 JAR 文件的位置由this.getClass().getProtectionDomain().getCodeSource().getLocation().

回答by Andrew Thompson

It is better to save files into a sub-directory of user.home than wherever the app. might reside.

最好将文件保存到 user.home 的子目录中,而不是应用程序的任何位置。可能居住。

Sun went to considerable effort to ensure that applets and apps. launched using Java Web Start cannot determine the apps. real path. This change broke many apps. I would not be surprised if the changes are extended to other apps.

Sun 付出了相当大的努力来确保小程序和应用程序。使用 Java Web Start 启动无法确定应用程序。真实路径。此更改破坏了许多应用程序。如果更改扩展到其他应用程序,我不会感到惊讶。

回答by Gary Rowe

The expression

表达方式

new File(".").getAbsolutePath();

will get you the current working directory associated with the execution of JVM. However, the JVM does provide a wealth of other useful properties via the

将为您提供与 JVM 执行相关的当前工作目录。但是,JVM 确实通过

System.getProperty(propertyName); 

interface. A list of these properties can be found here.

界面。可以在此处找到这些属性的列表。

These will allow you to reference the current users directory, the temp directory and so on in a platform independent manner.

这些将允许您以独立于平台的方式引用当前用户目录、临时目录等。

回答by I.Cougil

And what about using this.getClass().getProtectionDomain().getCodeSource().getLocation()?

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

回答by Mihir Patel

/*****************************************************************************
     * return application path
     * @return
     *****************************************************************************/
    public static String getApplcatonPath(){
        CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
        File rootPath = null;
        try {
            rootPath = new File(codeSource.getLocation().toURI().getPath());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return rootPath.getParentFile().getPath();
    }//end of getApplcatonPath()

回答by BullyWiiPlaza

Since the application path of a JARand an application running from inside an IDEdiffers, I wrote the following code to consistently return the correct current directory:

由于 aJAR和从 a 内部运行的应用程序的应用程序路径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;
    }
}

Simply call getProgramDirectory()and you should be good either way.

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

回答by Sahan

I use this method to get complete path to jar or exe.

我使用这种方法来获取 jar 或 exe 的完整路径。

File pto = new File(YourClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());

pto.getAbsolutePath());