java 如何获取Java程序的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4890687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the name of a Java program?
提问by Andy
I'm creating an application that could be either an .exe
or a .jar
and I need to know which it is. Does anyone know how I can get the file name/extension of a program running in Java please? I can get the path of the program running but I can't get the name.
我正在创建一个可以是 an.exe
或 a的应用程序,.jar
我需要知道它是哪个。有谁知道如何获取在 Java 中运行的程序的文件名/扩展名?我可以获得程序运行的路径,但我无法获得名称。
采纳答案by Victor Sorokin
Make 'name of program' a property that is passed to your program via '-D' command-line switch, like so
使“程序名称”成为通过“-D”命令行开关传递给程序的属性,如下所示
java -Dprogram.name=myApp.jar -jar myApp.jar
Read it in your code like so
像这样在你的代码中阅读它
if ("myApp.jar".equals(System.getProperty("program.name"))) {
// perform appropriate actions...
}
回答by Michael Borgwardt
The actual program running the JAR file would be java.exe
.
运行 JAR 文件的实际程序是java.exe
.
I suggest you approach the problem from a completely different angle and have the exe wrapper set a system property that the program queries. Or you could have it and the JAR manifest specify different main classes.
我建议你从一个完全不同的角度来解决这个问题,并让 exe 包装器设置一个程序查询的系统属性。或者你可以让它和 JAR 清单指定不同的主类。