在java中获取文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2914375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:26:52  来源:igfitidea点击:

Getting file path in java

javafile

提问by markovuksanovic

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

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

采纳答案by BalusC

You can use CodeSource#getLocation()for this. The CodeSourceis available by ProtectionDomain#getCodeSource(). The ProtectionDomainin turn is available by Class#getProtectionDomain().

您可以CodeSource#getLocation()为此使用。由CodeSource提供ProtectionDomain#getCodeSource()。该ProtectionDomain又是通过提供Class#getProtectionDomain()

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

This returns the exact location of the Classin question.

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

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#getResource()其中传递根包相对路径的位置。

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

You can even get it as an InputStreamusing ClassLoader#getResourceAsStream().

您甚至可以将其作为InputStreamusing 获取ClassLoader#getResourceAsStream()

InputStream input = classLoader.getResourceAsStream("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.extinstead.

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

回答by james

if you want to get the "working directory" for the currently running program, then just use:

如果您想获取当前正在运行的程序的“工作目录”,则只需使用:

new File("");

回答by Akabelle

For me this worked, when I knew what was the exact name of the file:

对我来说,这有效,当我知道文件的确切名称是什么时:

File f = new File("OutFile.txt");System.out.println("f.getAbsolutePath() = " + f.getAbsolutePath());

File f = new File("OutFile.txt");System.out.println("f.getAbsolutePath() = " + f.getAbsolutePath());

Or there is this solution too: http://docs.oracle.com/javase/tutorial/essential/io/find.html

或者也有这个解决方案:http: //docs.oracle.com/javase/tutorial/essential/io/find.html