Java 获取包含 main 的 .class 文件的目录路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/778187/
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
Getting directory path to .class file containing main
提问by Hamza Yerlikaya
Is it possible to get the path to my .class file containing my main function from within main?
是否可以从 main 中获取包含我的 main 函数的 .class 文件的路径?
采纳答案by erickson
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.
请注意,大多数类文件都被组装到 JAR 文件中,因此这不会在所有情况下都有效(因此IllegalStateException
. 但是,您可以使用此技术定位包含类的 JAR,并且您可以通过替换调用来获取类文件的内容,无论类是在文件系统上还是在 JARgetResourceAsStream()
中getResource()
,这都将起作用.
回答by Brian
According to http://www.cs.caltech.edu/courses/cs11/material/java/donnie/java-main.html, no. However, I suggest reading $0 (Program Name) in Java? Discover main class?, which at least gives you the main class .
根据http://www.cs.caltech.edu/courses/cs11/material/java/donnie/java-main.html,没有。但是,我建议在 Java 中阅读$0(程序名称)?发现主类?,这至少给了你主类。
回答by Michael Borgwardt
What do you need it for? If you need it to get hold of any files that are in the same directory, that's what Class.getResourceAsStream()is for.
你需要它做什么?如果您需要它来获取同一目录中的任何文件,这就是Class.getResourceAsStream()的用途。
回答by Randolf Richardson
That looks more like an end-user issue to me. Also consider the possible need to run multiple instances of any given application, and preventing users from doing so is going to become a major annoyance.
对我来说,这看起来更像是一个最终用户问题。还要考虑可能需要运行任何给定应用程序的多个实例,而阻止用户这样做将成为一个主要的烦恼。
If the problem is with temporary file conflicts, then just make sure all your temporary files have unique names. This, as I understand it, is the most common reason people feel a need to prevent multiple instances of their applications from running.
如果问题出在临时文件冲突上,那么只需确保所有临时文件的名称都是唯一的。据我所知,这是人们认为需要阻止其应用程序的多个实例运行的最常见原因。
P.S.: The java.io.File.createTempFile() methods are ideally suited for preventing temporary file conflicts because they automatically generate unique filenames.
PS:java.io.File.createTempFile() 方法非常适合防止临时文件冲突,因为它们会自动生成唯一的文件名。