I came across code that tries to read some configuration files from the same directory where the .class file is for the class itself:
File[] configFiles = new File(
this.getClass().getResource(".").getPath()).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
This seems to work in some cases (perhaps when running the code inside Resin), but for me, when launching Tomcat, it just fails with NPE because it getClass().getResource(".")returns null.
A colleague suggested creating another configuration file containing a list of all the ".xml" configuration files (which will really work here, since it remains fairly static), and that you should not try to do something like this in Java,
However, I am wondering if there is any good way that works everywhere to get the path to the directory where the given .class file is located? I think you could get it along the path of the .class file itself as follows:
new File(this.getClass().getResource("MyClass.class").getPath()).getParent()
... but is this the only / cleanest way?
Change . To clarify, suppose we know that this is used in an application deployed in such a way that MyClass.class will always be read from the .class file on disk, and the resources will be there in the same directory.
Jonik source
share