Search code examples
javamavenfileresources

How to get absolute path to file in /resources folder of your project


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?


Solution

  • You can use ClassLoader.getResource method to get the correct resource.

    URL res = getClass().getClassLoader().getResource("abc.txt");
    File file = Paths.get(res.toURI()).toFile();
    String absolutePath = file.getAbsolutePath();
    

    OR

    Although this may not work all the time, a simpler solution -

    You can create a File object and use getAbsolutePath method:

    File file = new File("resources/abc.txt");
    String absolutePath = file.getAbsolutePath();