Languages
[Edit]
EN

Java - get file absolute path according to indicated class

4 points
Created by:
Abel-Burks
758

In this short article, we would like to show how to find file absolute path according to indicated class in Java.

Usage example:

String path = PathUtils.getAbsolutePath(MyClass.class, "file.txt");  // check the below source code

System.out.println(path);  // C:/projects/test/target/classes/com/example/file.txt

 

Java Maven project structure.
Java Maven project structure.

Assumptions

Java project was located in C:/projects/test directory. Java files were located in src/com/example directory according to used com.example package.

Solution

Program.java file:

package com.example;

public class Program {
    
    public static void main(String[] args) {

        String path = PathUtils.getAbsolutePath(Program.class, "file.txt");
        System.out.println(path);  // C:/projects/test/target/classes/com/example/file.txt
    }
}

Notes:

  • by default, each class file after compilation is placed in out/ or output/ directory (target/ for maven project),
  • to know how to configure *.txt files coppying go to this article.

Example output:

C:/projects/test/target/classes/com/example/file.txt

 

PathUtils.java file:

package com.example;

import java.net.URL;

public class PathUtils {
    
    private static final boolean IS_WINDOWS;

    static {
        String OS_NAME = System.getProperty("os.name");
        String OS_CODE = OS_NAME.toLowerCase();
        IS_WINDOWS = OS_CODE.contains("win");
    }

    private PathUtils() {
        // Nothing here ...
    }

    public static String getAbsolutePath(Class<?> clazz, String relativePath) {
        URL url = clazz.getResource(relativePath);
        if (url == null) {
            return null;
        }
        String path = url.getPath();
        if (IS_WINDOWS) {
            return path.substring(1);
        }
        return path;
    }
}

 

Alternative titles

  1. Java - find file absolute path according to indicated class
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join