Is there a way for java program to determine its location in the file system?
How to get the filepath of a file in Java By mkyong| Last updated: August 24, 2020 Viewed: 516,464 (+5,406 pv/w) Tags:filepath| java.io| java.nio| symbolic link In Java, for NIO Path, we can use path.toAbsolutePath()to get the file path; For legacy IO File, we can use file.getAbsolutePath()to get the file path.
The Path class forms part of the NIO2 update, which came to Java with version 7. It delivers an entirely new API to work with I/O. Moreover, like the legacy File class, Path also creates an object that may be used to locate a file in a file system. Likewise, it can perform all the operations that can be done with the File class:
System.out.println ("File path: " + new File ("Your file name").getAbsolutePath ()); The File class has several more methods you might find useful. Correct solution with "File" class to get the directory - the "path" of the file: String path = new File ("C:\Temp\your directory\yourfile.txt").getParent (); getParent () returns a String.
Last Updated : 30 Jan, 2019 The getPath () method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With