我需要做的是获取正在运行的 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?
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());</p>
在编译的应用程序中返回简单路径并在 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('!')));
}
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
应该给你罐子。
至于 exe,因为我假设您正在使用某种包装器,所以您需要在运行之前知道 exe 的名称。然后你可以使用类似的东西:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
尝试以下
System.getProperty("java.class.path")
使用Lunch4j,您可以通过编辑生成的xml为exe文件添加图像名称,您必须将标记值true从false更改为true