在java中获取文件路径

mar*_*vic 10 java file

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

Bal*_*usC 13

你可以用CodeSource#getLocation()它.该CodeSource可通过ProtectionDomain#getCodeSource().该ProtectionDomain又是通过提供Class#getProtectionDomain().

URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
File file = new File(location.getPath());
// ...
Run Code Online (Sandbox Code Playgroud)

这将返回有问题的确切位置Class.

更新:根据评论,它显然已经在类路径中.然后,您可以使用ClassLoader#getResource()其中传递根包相对路径.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("filename.ext");
File file = new File(resource.getPath());
// ...
Run Code Online (Sandbox Code Playgroud)

你甚至可以把它作为一个InputStream使用ClassLoader#getResourceAsStream().

InputStream input = classLoader.getResourceAsStream("filename.ext");
// ...
Run Code Online (Sandbox Code Playgroud)

这也是使用打包资源的常规方式.如果它位于包内,则使用例如com/example/filename.ext代替.