EN
Java - get file absolute path according to indicated class
4
points
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

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/
oroutput/
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;
}
}