获取应用程序的路径 [英] Get the application's path

查看:65
本文介绍了获取应用程序的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近搜索了如何在Java中获取应用程序的目录.我终于找到了答案,但是我需要很长的时间,因为搜索这样一个通用术语并不容易.我认为最好汇编一下以多种语言实现此目标的列表.

I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.

如果您(不喜欢)这个主意,可以随意上/下投票;如果您喜欢,请贡献.

Feel free to up/downvote if you (don't) like the idea and please contribute if you like it.

包含可执行文件的目录当前工作目录(在Unix下由pwd给出)之间有很好的区别.我最初对前者感兴趣,但也可以随意发布确定后者的方法(阐明您的意思).

There's a fine distinction between the directory that contains the executable file and the current working directory (given by pwd under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).

推荐答案

Java 中的调用

System.getProperty("user.dir")

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

返回当前工作目录.

致电

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

返回包含当前类的JAR文件的路径,如果直接从文件系统运行,则返回产生当前类的CLASSPATH元素(路径).

returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that yielded the current class if you're running directly from the filesystem.

示例:

  1. 您的应用程序位于

  1. Your application is located at

 C:\MyJar.jar

  • 打开外壳程序(cmd.exe),并cd到C:\ test \ subdirectory.

  • Open the shell (cmd.exe) and cd to C:\test\subdirectory.

    使用命令java -jar C:\MyJar.jar启动应用程序.

    Start the application using the command java -jar C:\MyJar.jar.

    前两个调用返回'C:\ test \ subdirectory';第三次调用返回"C:\ MyJar.jar".

    The first two calls return 'C:\test\subdirectory'; the third call returns 'C:\MyJar.jar'.

    从文件系统而不是JAR文件运行时,结果将是生成的类文件根目录的路径,例如

    When running from a filesystem rather than a JAR file, the result will be the path to the root of the generated class files, for instance

    c:\eclipse\workspaces\YourProject\bin\
    

    该路径不包括生成的类文件的软件包目录.

    The path does not include the package directories for the generated class files.

    获取不带.jar文件名的应用程序目录的完整示例,或者直接从文件系统运行(例如在调试时)的类文件的相应路径:

    A complete example to get the application directory without .jar file name, or the corresponding path to the class files if running directly from the filesystem (e.g. when debugging):

    String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 
    
    if (applicationDir.endsWith(".jar"))
    {
        applicationDir = new File(applicationDir).getParent();
    }
    // else we already have the correct answer
    

    这篇关于获取应用程序的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆