开发者

Getting file path in java

开发者 https://www.devze.com 2022-12-31 22:35 出处:网络
Is there a way for java program to determine its location in the fil开发者_开发百科e system?You can use CodeSource#getLocation() for this. The CodeSource is available by ProtectionDomain#getCodeSource

Is there a way for java program to determine its location in the fil开发者_开发百科e system?


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

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

This returns the exact location of the Class in question.

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 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 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.


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

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


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

new File("");
0

精彩评论

暂无评论...
验证码 换一张
取 消