2010-05-26 104 views

回答

11

您可以使用CodeSource#getLocation()CodeSource可通过ProtectionDomain#getCodeSource()获得。 ProtectionDomain又可通过Class#getProtectionDomain()获得。

URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); 
File file = new File(location.getPath()); 
// ... 

这将返回Class问题的确切位置。

更新:根据评论,它显然已经在类路径中。然后您可以使用ClassLoader#getResource(),其中您传递了根目录相对路径。

ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
URL resource = classLoader.getResource("filename.ext"); 
File file = new File(resource.getPath()); 
// ... 

你甚至可以把它作为使用ClassLoader#getResourceAsStream()InputStream

InputStream input = classLoader.getResourceAsStream("filename.ext"); 
// ... 

这也是使用打包资源的正常方式。如果它位于包装内,则改为使用com/example/filename.ext

+1

+1,但注意p rotectionDomain.getCodeSource()和CodeSource.getLocation()都可以为null。 – 2010-05-26 18:22:28

+0

@bkail:当它使用设计不佳的本土类加载器加载时,或者从某个外部流源加载时,它确实可能会返回null。但是,这通常不适用于具有'main() '。 – BalusC 2010-05-26 18:26:44

+0

这绝对是做这份工作 - 但它看起来不太好。我需要做的是加载一个配置文件,它需要与我的jar文件在同一个文件夹中,但可以从任何位置运行。这是获取文件位置信息的正确方法吗? – markovuksanovic 2010-05-26 21:34:02

-1

,如果你想获得当前正在运行的程序“工作目录”,然后只需使用:

new File(""); 
+2

工作目录不一定在程序所在的位置。 – Douglas 2012-02-28 15:57:11