在java中获取文件路径 [英] Getting file path in java

查看:150
本文介绍了在java中获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java程序有没有办法确定它在文件系统中的位置?

Is there a way for java program to determine its location in the file system?

推荐答案

你可以使用 CodeSource#getLocation( ) CodeSource 可通过 的ProtectionDomain#getCodeSource() ProtectionDomain 反过来可以通过 Class#getProtectionDomain()

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());
// ...

这将返回类有问题。

更新:根据评论,它显然已经在类路径中了。然后你可以使用 ClassLoader #getResource() ,其中传递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 使用 ClassLoader#getResourceAsStream()

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中获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆