Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get absolute path of file from stack trace

I have a Java print stack trace function that I use for debugging.

private static void printError(String message, Significance severityLevel, int stackTraceStart) {
    final String thread_name = Thread.currentThread().getName();
    final String location_of_print_statement = Thread.currentThread().getStackTrace()[stackTraceStart].toString();
    Package_Private.printLineToReadout("\n" + "Thread \"" + thread_name + "\": "
            + location_of_print_statement + "\n" + message, ReadoutCondition.BAD, severityLevel);
}

Problem is that it only prints "modules.ShopModule.configure(ShopModule.scala:8)"

I want it to print the entire path to that file, not the relative path.

like image 222
Michael Lafayette Avatar asked Nov 09 '22 20:11

Michael Lafayette


1 Answers

A little bit too late, but might be useful for someone else. You can use the ClassLoader to search for the resource corresponding to a specific class file.

import static java.lang.System.out;
import java.util.Arrays;
import java.net.URL;

public class Abs {
  public static void main(String[] args){
    Arrays.asList(Thread.currentThread().getStackTrace()).stream().forEach(e -> {
      String cn = e.getClassName().replace('.', '/') + ".class";
      URL u = new Abs().getClass().getClassLoader().getResource(cn);
      out.println("" + u.toString().replace(".class", ".java") + ":" + e.getLineNumber());
    });
  }
}

Similar discussion is here: Possible to get the file-path of the class that called a method in Java? and here What is the difference between Class.getResource() and ClassLoader.getResource()?

like image 152
chaws Avatar answered Nov 14 '22 21:11

chaws