Java程序有办法确定自己在文件系统中的位置吗?
CodeSource#getLocation()
方法来实现这个功能。通过 ProtectionDomain#getCodeSource()
方法可以获取到相应的 CodeSource
对象。而获取 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
,例如。
这对我来说很有效,当我知道文件的确切名称时:
File f = new File("OutFile.txt");
System.out.println("f.getAbsolutePath() = " + f.getAbsolutePath());
或者还有这个解决方案:http://docs.oracle.com/javase/tutorial/essential/io/find.html
如果您想获取当前运行程序的“工作目录”,则只需使用:
new File("");
main()
的“具体”Java程序。 - BalusC