问题描述
java程序有没有办法确定它在文件系统中的位置?
Is there a way for java program to determine its location in the file system?
推荐答案
你可以使用。 可通过。 反过来可以通过。
You can use CodeSource#getLocation()
for this. The CodeSource
is available by ProtectionDomain#getCodeSource()
. The ProtectionDomain
in turn is available by Class#getProtectionDomain()
.
URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
File file = new File(location.getPath());
// ...
这将返回类有问题。
更新:根据评论,它显然已经在类路径中了。然后你可以使用,其中传递root-package-relative路径。
Update: as per the comments, it's apparently already in the classpath. You can then just use ClassLoader#getResource()
wherein you pass the root-package-relative path.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("filename.ext");
File file = new File(resource.getPath());
// ...
您甚至可以将其作为 InputStream 使用。
You can even get it as an InputStream
using ClassLoader#getResourceAsStream()
.
InputStream input = classLoader.getResourceAsStream("filename.ext");
// ...
这也是使用打包资源的常规方式。如果它位于包内,则使用例如 com / example / filename.ext
代替。
That's also the normal way of using packaged resources. If it's located inside a package, then use for example com/example/filename.ext
instead.
这篇关于在java中获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!