在java中获取文件路径

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

您可以使用CodeSource#getLocation()CodeSource可通过ProtectionDomain#getCodeSource() 。 然后, Class#getProtectionDomain()可以使用ProtectionDomain

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

这将返回相关类的确切位置。

更新 :根据评论,它显然已经在类路径中。 然后,您可以使用ClassLoader#getResource()其中传递root-package-relative路径。

 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("");