【发布时间】:2018-11-23 14:41:50
【问题描述】:
我需要做的是获取正在运行的 jar/exe 文件的名称(在 windows 上是 EXE,在 mac/linux 上是 jar)。我一直在四处寻找,但似乎无法找到方法。
如何获取正在运行的 Jar 或 Exe 的名称?
【问题讨论】:
我需要做的是获取正在运行的 jar/exe 文件的名称(在 windows 上是 EXE,在 mac/linux 上是 jar)。我一直在四处寻找,但似乎无法找到方法。
如何获取正在运行的 Jar 或 Exe 的名称?
【问题讨论】:
希望这对您有所帮助,我测试了代码并返回完整路径和名称。
也许你想多玩一点代码并给我一些反馈。
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
这是在 stackoverflow 上的一个类似但不是 == 问题上找到的 How to get the path of a running JAR file?
【讨论】:
文件(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
在编译后的应用程序中返回简单路径并在 jar 中返回错误:
URI 不是分层的
我的解决办法是:
private File getJarFile() throws FileNotFoundException {
String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n" + path);
}
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return new File(path.substring(0, path.lastIndexOf('!')));
}
【讨论】:
class.getProtectionDomain().getCodeSource().getLocation(), 和其他一切都返回了rsrc:.。
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
应该把罐子给你。
至于 exe,因为我假设您正在使用某种包装器,所以您需要在运行之前知道 exe 的名称。然后你可以使用类似的东西:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
【讨论】:
ProcessBuilder创建Process。
试试下面的
System.getProperty("java.class.path")
【讨论】:
使用Lunch4j 你可以通过编辑生成的xml为exe文件添加一个图像名称,你必须将标签值true从false更改为true
【讨论】: