如何在Java(IDE)中找到当前项目目录的路径?

80

我正在尝试以编程方式在Java中定位当前运行/调试的项目路径,我在 Google 中查找到的是System.getProperty("user.id"),但无法获取该项目的路径。

我知道在C#中使用命令Environment.currentDirectory可以给出当前运行/调试的项目路径,所以我相信在Java中也必须有类似的方法。

因此,我想问是否有人能告诉我或给我一段代码来程序化地查找当前运行/调试的项目路径?

编辑: 我正在编写一个插件,它与Eclipse启动一起加载。该插件向Eclipse的工作台添加一个按钮,在插件的代码中,当我单击该按钮时,我搜索当前目录路径。

我的目的是,例如当我调试项目然后单击该按钮时,会弹出一个窗口,显示正在调试的项目路径,谢谢。


如果你不知道如何获取当前工作目录,就不应该编写Eclipse插件。我真的看不出“打开项目文件夹”按钮有什么用处,因为调试器透视图已经会打开正确的源文件并定位到正确的行。当然,这是你的时间和精力。你可能想花更多的时间学习Eclipse,而不是通过一个有点无用的插件来拖慢它的速度,从而自己给自己惹麻烦。 - Shark
我想我已经弄清楚为什么这些示例不起作用了,因为它打印出的是插件目录而不是正在调试的项目。不过我想我已经找到了其他的方法,感谢大家的帮助。 - user1765376
9个回答

136

两种方法

System.getProperty("user.dir");
或者这个。
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch block

这个想法是使用"."获取当前文件夹,然后获取它的绝对路径并从中删除文件名,因此可以得到类似于以下内容的结果:

/home/shark/eclipse/workspace/project/src/com/package/name/bin/Class.class

当你移除 Class.class 后,你将得到

/home/shark/eclipse/workspace/project/src/com/package/name/bin/

这是你想要的。


如果我想要的是src路径而不是bin路径呢? - Moesio
答案的第二点不是问题的答案,第一点是。支持此答案:https://dev59.com/0mcs5IYBdhLWcg3wPxnN#22011009 - Marco Sulla

42
使用Java获取项目位置的关键是使用user.dir键。 代码:
System.out.println("Present Project Directory : "+ System.getProperty("user.dir"));

输出:

当前项目目录:C:\workspace\MyEclipse 10\examples\MySqlMavenDomain

要显示所有系统属性,只需使用System.getProperties();

使用System.getProperty("java.version");中的Key值获取输出。

代码:

Properties properties = System.getProperties();
Enumeration<Object> enumeration = properties.keys();
for (int i = 0; i < properties.size(); i++) {
    Object obj = enumeration.nextElement();
    System.out.println("Key: "+obj+"\tOutPut= "+System.getProperty(obj.toString()));
}

输出:

Key: java.runtime.name  OutPut= Java(TM) SE Runtime Environment
Key: sun.boot.library.path  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\bin
Key: java.vm.version    OutPut= 24.45-b08
Key: java.vm.vendor OutPut= Oracle Corporation
Key: java.vendor.url    OutPut= http://java.oracle.com/
Key: path.separator OutPut= ;
Key: java.vm.name   OutPut= Java HotSpot(TM) Client VM
Key: file.encoding.pkg  OutPut= sun.io
Key: user.country   OutPut= US
Key: user.script    OutPut= 
Key: sun.java.launcher  OutPut= SUN_STANDARD
Key: sun.os.patch.level OutPut= Service Pack 3
Key: java.vm.specification.name OutPut= Java Virtual Machine Specification
Key: user.dir   OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain
Key: java.runtime.version   OutPut= 1.7.0_45-b18
Key: java.awt.graphicsenv   OutPut= sun.awt.Win32GraphicsEnvironment
Key: java.endorsed.dirs OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\endorsed
Key: os.arch    OutPut= x86
Key: java.io.tmpdir OutPut= C:\DOCUME~1\UDAYP~2.PBS\LOCALS~1\Temp\
Key: line.separator OutPut= 

Key: java.vm.specification.vendor   OutPut= Oracle Corporation
Key: user.variant   OutPut= 
Key: os.name    OutPut= Windows XP
Key: sun.jnu.encoding   OutPut= Cp1252
Key: java.library.path  OutPut= C:\Program Files\Java\jdk1.7.0_45\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin/client;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin;C:/Program Files/MyEclipse/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;D:\Program Files\Microsoft SQL Server\100\Tools\Binn\;D:\Program Files\Microsoft SQL Server\100\DTS\Binn\;.
Key: java.specification.name    OutPut= Java Platform API Specification
Key: java.class.version OutPut= 51.0
Key: sun.management.compiler    OutPut= HotSpot Client Compiler
Key: os.version OutPut= 5.1
Key: user.home  OutPut= C:\Documents and Settings\uday.p.PBSYSTEMS
Key: user.timezone  OutPut= 
Key: java.awt.printerjob    OutPut= sun.awt.windows.WPrinterJob
Key: file.encoding  OutPut= UTF-8
Key: java.specification.version OutPut= 1.7
Key: java.class.path    OutPut= C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\test-classes;C:\workspace\MyEclipse 10\examples\MySqlMavenDomain\target\classes;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\jstl\jstl\1.2\jstl-1.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\servlet\javax.servlet-api\3.1.0\javax.servlet-api-3.1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\mysql\mysql-connector-java\5.1.28\mysql-connector-java-5.1.28.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\mail\mail\1.4.7\mail-1.4.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\javax\activation\activation\1.1\activation-1.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\junit\junit\4.11\junit-4.11.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-core\4.3.0.Final\hibernate-core-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging\3.1.3.GA\jboss-logging-3.1.3.GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\logging\jboss-logging-annotations\1.2.0.Beta1\jboss-logging-annotations-1.2.0.Beta1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.0.0.Final\jboss-transaction-api_1.2_spec-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\xml-apis\xml-apis\1.0.b2\xml-apis-1.0.b2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\common\hibernate-commons-annotations\4.0.4.Final\hibernate-commons-annotations-4.0.4.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.0.Final\hibernate-jpa-2.1-api-1.0.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\javassist\javassist\3.18.1-GA\javassist-3.18.1-GA.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\jboss\jandex\1.1.0.Final\jandex-1.1.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\hibernate\hibernate-entitymanager\4.3.0.Final\hibernate-entitymanager-4.3.0.Final.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-dbcp\commons-dbcp\1.4\commons-dbcp-1.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-fileupload\commons-fileupload\1.3\commons-fileupload-1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-io\commons-io\2.4\commons-io-2.4.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-net\commons-net\3.3\commons-net-3.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-pool\commons-pool\1.6\commons-pool-1.6.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\commons-beanutils\commons-beanutils\1.9.0\commons-beanutils-1.9.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\apache\commons\commons-lang3\3.1\commons-lang3-3.1.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\log4j\log4j\1.2.16\log4j-1.2.16.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-orm\3.2.6.RELEASE\spring-orm-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-jdbc\3.2.6.RELEASE\spring-jdbc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-tx\3.2.6.RELEASE\spring-tx-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-web\3.2.6.RELEASE\spring-web-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aop\3.2.6.RELEASE\spring-aop-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-webmvc\3.2.6.RELEASE\spring-webmvc-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-aspects\3.2.6.RELEASE\spring-aspects-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\aspectj\aspectjweaver\1.7.2\aspectjweaver-1.7.2.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-beans\3.2.6.RELEASE\spring-beans-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context\3.2.6.RELEASE\spring-context-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-context-support\3.2.6.RELEASE\spring-context-support-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-core\3.2.6.RELEASE\spring-core-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-expression\3.2.6.RELEASE\spring-expression-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument\3.2.6.RELEASE\spring-instrument-3.2.6.RELEASE.jar;C:\Documents and Settings\uday.p.PBSYSTEMS\.m2\repository\org\springframework\spring-instrument-tomcat\3.2.6.RELEASE\spring-instrument-tomcat-3.2.6.RELEASE.jar
Key: user.name  OutPut= uday.p
Key: java.vm.specification.version  OutPut= 1.7
Key: sun.java.command   OutPut= com.uk.mysqlmaven.domain.test.UserLoginDetails
Key: java.home  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre
Key: sun.arch.data.model    OutPut= 32
Key: user.language  OutPut= en
Key: java.specification.vendor  OutPut= Oracle Corporation
Key: awt.toolkit    OutPut= sun.awt.windows.WToolkit
Key: java.vm.info   OutPut= mixed mode, sharing
Key: java.version   OutPut= 1.7.0_45
Key: java.ext.dirs  OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
Key: sun.boot.class.path    OutPut= C:\Program Files\Java\jdk1.7.0_45\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0_45\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.7.0_45\jre\classes
Key: java.vendor    OutPut= Oracle Corporation
Key: file.separator OutPut= \
Key: java.vendor.url.bug    OutPut= http://bugreport.sun.com/bugreport/
Key: sun.io.unicode.encoding    OutPut= UnicodeLittle
Key: sun.cpu.endian OutPut= little
Key: sun.desktop    OutPut= windows
Key: sun.cpu.isalist    OutPut= pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

更多细节请参见类System


我正在Tomcat服务器上运行我的项目。因此,当我使用System.getProperty("user.dir")时,它会给我Tomcat服务器的路径。有没有一种方法可以获取项目文件夹的路径? - Dilini Peiris
@DiliniPeiris 你可以在这里找到答案:https://dev59.com/j2w15IYBdhLWcg3w6f80 - UdayKiran Pulipati

14

这是新的做法:

Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);

或者更好的:

Path root = Paths.get(".").normalize().toAbsolutePath();

但我会更进一步:

public Path getUsersProjectRootDirectory() {
    String envRootDir = System.getProperty("user.dir");
    Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
    if ( rootDir.startsWith(envRootDir) ) {
        return rootDir;
    } else {
        throw new RuntimeException("Root dir not found in user directory.");
    }
}

8

System.getProperty("user.dir")是什么?它将为您提供程序启动的工作目录。

请参阅Java教程中的系统属性,了解Java的系统属性概述。


我已经尝试过了,它没有给出当前目录路径,但是它会给出包含Eclipse项目的目录路径。 - user1765376
“当前目录路径”是什么意思?使用这段代码,你将获得程序启动的目录 - 是的,Eclipse通常会从磁盘上存储项目的目录中启动你的程序。 - mthmulders
我已经编辑了上面的信息,希望它能够解释清楚一切。 - user1765376
如果您想要获取调试开始的目录,可以使用上面的方法。如果您需要查找项目路径,可以假设它与调试开始的目录相同,或者使用Eclipse插件API来查找。不幸的是,我不熟悉任何Eclipse插件API,所以无法提供帮助。 - mthmulders
上述命令在我将其放入插件并尝试调试项目时没有帮助,然后单击我的插件按钮,无论如何还是谢谢。 - user1765376

5

你做不到。

Java项目没有一个路径! Java项目有多个路径,即使一个类在同一个“项目”的不同类路径中可以有多个位置。

因此,如果您在JRE / lib中有一个名为calculator.jar的文件,并且在CD上有一个包含相同类的calculator.jar:如果执行calculator.jar,则java虚拟机将从JRE / lib中获取类而非CD中的类!

这个问题经常出现在喜欢加载项目内部资源的程序员身上。在这种情况下,

System.getResource("/likebutton.png") 

以此为例。


方法getResource(String)对类型System未定义。 - Quatsch
从classpath获取路径与从JVM/系统获取路径是不同的。 - djangofan

3
这是一个Java代码片段,用于获取当前正在运行的Web应用程序项目的路径。
public String getPath() throws UnsupportedEncodingException {

    String path = this.getClass().getClassLoader().getResource("").getPath();
    String fullPath = URLDecoder.decode(path, "UTF-8");
    String pathArr[] = fullPath.split("/WEB-INF/classes/");
    System.out.println(fullPath);
    System.out.println(pathArr[0]);
    fullPath = pathArr[0];

    return fullPath;

}

来源:https://dzone.com/articles/get-current-web-application

本文将介绍如何使用Java Servlet API中的方法来获取当前正在运行的Web应用程序的名称。要获取当前Web应用程序的名称,只需调用ServletContext.getContextPath()方法即可。该方法返回Web应用程序的上下文路径,该路径是Web应用程序在Web服务器上的部署位置。


3

您可以使用System.getProperty("user.dir")获取当前项目路径。

在该方法中,您可以编写键名以获取不同的路径,如果您不知道键名,可以使用System.getProperties()查找所有属性名称。该方法将返回所有带有键的属性,并且您可以从中手动查找键名。

然后编写System.getProperty("KEY NAME"),并获取所需的路径。


2
File currDir = new File(".");
String path = currDir.getAbsolutePath();
System.out.println(path);

这将在结尾打印.。要删除它,只需将字符串截断一个字符,如下所示:
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
System.out.println(path);

它会在路径末尾打印一个“.”。 - mthmulders
1
@mthmulders:我只是在分享这个概念。添加了 substring() 函数来截取末尾的 . - Yogendra Singh
我已经尝试过了。我已经编辑了上面主题的信息,希望能更好地解释一切,谢谢。 - user1765376
尝试使用“getCanonicalPath()”函数来解析相对路径。 - Rex the Strange

1
我刚刚使用了这个:
System.out.println(System.getenv().get("PWD"));

使用 OpenJDK 11


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接