在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
Getting file path in java
提问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 CodeSource
is available by ProtectionDomain#getCodeSource()
. The ProtectionDomain
in 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 Class
in 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 InputStream
using ClassLoader#getResourceAsStream()
.
您甚至可以将其作为InputStream
using 获取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.ext
instead.
这也是使用打包资源的正常方式。如果它位于包内,则使用 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