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

问题描述 投票:35回答:13

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

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

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

java filepath
13个回答
45
投票

尝试;

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

0
投票

如果你想获得Java Web应用程序的真正路径,比如Spring(Servlet),你可以从你的HttpServletRequest附带的Servlet Context对象中获取它。

@GetMapping("/")
public String index(ModelMap m, HttpServletRequest request) {
    String realPath = request.getServletContext().getRealPath("/");
    System.out.println(realPath);
    return "index";
}

-1
投票

如果你想使用这个答案:https://stackoverflow.com/a/4033033/10560907

您必须添加如下导入语句:

import java.io.File;

在最开始的java源代码中。

像这样的答案:https://stackoverflow.com/a/43553093/10560907


-1
投票

我在类路径的根目录下有一个“cost.ini”文件。我的JAR文件名为“cost.jar”。

以下代码:

  • 如果我们有一个JAR文件,请获取JAR文件所在的目录。
  • 如果我们有* .class文件,则获取类的根目录。
try {
    //JDK11: replace "UTF-8" with UTF_8 and remove try-catch
    String rootPath = decode(getSystemResource("cost.ini").getPath()
            .replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
    showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}

.getPath()返回的路径格式为:

  • 在JAR:file:/C:/folder1/folder2/cost.jar!/cost.ini
  • 在* .class:/C:/folder1/folder2/cost.ini 如果应用程序以JAR格式提供,则每次使用File都会导致异常。

  • -2
    投票

    表达方式

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

    将获得与JVM执行相关的当前工作目录。但是,JVM确实通过提供了大量其他有用的属性

    System.getProperty(propertyName); 
    

    接口。这些属性列表can be found here

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


    30
    投票

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

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

    9
    投票

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


    4
    投票

    如果您正在谈论Web应用程序,则应使用getRealPath对象中的ServletContext

    例:

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

    希望这可以帮助。


    1
    投票

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

    Sun付出了相当大的努力来确保applet和app。使用Java Web Start启动无法确定应用程序。真正的道路。这一变化打破了许多应用。如果将更改扩展到其他应用程序,我不会感到惊讶。


    1
    投票
    /*****************************************************************************
         * 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()
    

    1
    投票

    由于JAR的应用程序路径和从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;
        }
    }
    

    只需致电getProgramDirectory(),无论哪种方式都应该是好的。


    1
    投票

    我使用这个方法获得jar或exe的完整路径。

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

    0
    投票
    new File(".").getAbsolutePath()
    
    © www.soinside.com 2019 - 2024. All rights reserved.