1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public static File getClassRootDirectory(Class<?> clazz) throws URISyntaxException {
final String resName = "/" + clazz.getName().replace('.', '/') + ".class";
final String url = clazz.getResource(resName).toString();
if (url.startsWith("file:")) {
// Cas d'un fichier simple
// On récupère le répertoire de base :
int index = url.lastIndexOf(resName);
if (index>=5) {
System.err.println(url.substring(5, index+1));
return new File(url.substring(5, index+1));
}
} else if (url.startsWith("jar:file:")) {
// Cas d'une archive JAR/ZIP
// On récupère le fichier compréssé :
int index = url.lastIndexOf('!');
if (index>=9) {
return new File(url.substring(9, index)).getParentFile();
}
}
// On ne gère pas tous les autres cas :
throw new IllegalStateException("Unsupported URL : " + url);
} |