您可以使用CodeSource#getLocation()为了这。这CodeSource可以通过ProtectionDomain#getCodeSource(). The ProtectionDomain反过来又可以通过Class#getProtectionDomain().
URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
File file = new File(location.getPath());
// ...
这将返回的确切位置Class
有问题。
Update:根据评论,它显然已经在类路径中。然后你就可以使用ClassLoader#getResource()其中传递根包相对路径。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("filename.ext");
File file = new File(resource.getPath());
// ...
您甚至可以将其作为InputStream
using ClassLoader#getResourceAsStream().
InputStream input = classLoader.getResourceAsStream("filename.ext");
// ...
这也是使用打包资源的正常方式。如果它位于包内,则使用例如com/example/filename.ext
反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)