java 获取程序路径,如何获取运行java程序的路径

本文介绍如何在Java程序运行时获取主类的路径。通过使用`Test.class.getClassLoader().getResource(foo/Test.class)`可以打印出类文件的路径。如果需要获取包含主类的JAR路径,可以使用类似的技术,但需要注意大多数类文件可能已打包到JAR中。此外,`System.getProperty(java.class.path)`返回的是类路径,包括目录和JAR文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Is there a way to get the path of main class of the running java program.

structure is

D:/

|---Project

|------bin

|------src

I want to get the path as D:\Project\bin\.

I tried System.getProperty("java.class.path"); but the problem is, if I run like

java -classpath D:\Project\bin;D:\Project\src\ Main

Output

Getting : D:\Project\bin;D:\Project\src\

Want : D:\Project\bin

Is there any way to do this?

===== EDIT =====

Got the solution here

package foo;

public class Test

{

public static void main(String[] args)

{

ClassLoader loader = Test.class.getClassLoader();

System.out.println(loader.getResource("foo/Test.class"));

}

}

This printed out:

file:/C:/Users/Jon/Test/foo/Test.class

URL main = Main.class.getResource("Main.class");

if (!"file".equalsIgnoreCase(main.getProtocol()))

throw new IllegalStateException("Main class is not stored in a file.");

File path = new File(main.getPath());

Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.

解决方案

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files.

Elements of the class path are separated by a platform-specific

character specified in the path.separator property.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值