I'm trying to print the current path of class that executes main(), as below. I found the statements below from googling, but doesn't work in my computer(windows+intellij)
public class core3 {
public static void main(String[] args) {
try {
URL url = new core3().getClass().getClassLoader().getResource("");
System.out.println(url);
System.out.println(System.getProperty(url.getPath()));//print null
} catch (Exception e) {
e.printStackTrace();
}
}
}
Actually it prints
file:/D:/Documents/myproject/test01/target/classes/
null
Why the second print returns null? How to fix it?
Thanks
System.getProperty() is for getting system properties. For example, the "java.home" system property typically points to the location of your Java installation. System properties are described here.
Your code is looking up a system property with key equal to your URL. You do not have such a system property defined, so System.getProperty()
returns null
.
If you just want to print the path, you should simply omit the System.getProperty()
call:
System.out.println(url.getPath());