Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file path in java

Tags:

java

file

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

like image 817
markovuksanovic Avatar asked May 26 '10 15:05

markovuksanovic


People also ask

How to get the filepath of a file in Java?

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.

What is the path class in Java?

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:

How to get the absolute path of a file in Java?

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.

What is the use of getpath() method in Java?

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.


1 Answers

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.

like image 89
BalusC Avatar answered Oct 25 '22 02:10

BalusC