Assume standard maven setup.
Say in your resources folder you have a file abc
.
In Java, how can I get absolute path to the file please?
Assume standard maven setup.
Say in your resources folder you have a file abc
.
In Java, how can I get absolute path to the file please?
You can create a File
object and use getAbsolutePath
method:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath())
doesn't work for all paths! The path is still URL-encoded!)
You must specifie path started from /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath()
method of that class.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
To return a file or filepath
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path