我知道有很多类似的问题和答案。但没有一种解决方案适合我!我不明白为什么(( 所以我有可运行的 jar,例如“program.jar”,在其中我想获取该 jar 的名称(即 program.jar)。我尝试过以下操作:
ClassInsideJar.class.getProtectionDomain().getCodeSource().getLocation().getPath()
new java.io.File(ClassInsideJar.class.getProtectionDomain().getCodeSource().getLocation().getPath())
new File(".")).getAbsolutePath()
(以及不同的变体,如 getCanonicalPath 等)ClassLoader.getSystemClassLoader().getResource(".").getPath()
在所有这些情况下,我只能选择这个 jar 的路径。例如完整路径是J:/folder/program.jar
。我只能看到 J:/folder
。
有什么错误吗?我正在尝试获取主类和其他类中 jar 的名称。
我尝试通过双击和命令行来运行这个jar。结果是一样的
最佳答案
试试这个:
(new File(ClassInsideJar.class.getProtectionDomain().getCodeSource().getLocation().toURI())).getName();
关于java - 无法获取正在运行的 jar 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24455104/