1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| package osteo;
import java.net.URL;
import java.net.URLDecoder;
/**
* @author
*
*/
public class TestLocation
{
static
{
try
{
String path = TestLocation.class.getName() + ".class";
URL url = TestLocation.class.getResource(path);
path = URLDecoder.decode(url.toString(), "UTF-8");
// suppression de la classe ou du jar du path de l'url
int index = path.lastIndexOf("/");
path = path.substring(0, index);
if (path.startsWith("jar:file:"))
{
// suppression de jar:file: de l'url d'un jar
// ainsi que du path de la classe dans le jar
index = path.indexOf("!");
path = path.substring(9, index);
}
else
{
// suppresion du file: de l'url si c'est une classe en dehors d'un jar
// et suppression du path du package si il est présent.
path = path.substring(5, path.length());
Package pack = TestLocation.class.getPackage();
if (null != pack)
{
String packPath = pack.toString().replace('.', '/');
if (path.endsWith(packPath))
{
path = path.substring(0, (path.length() - packPath.length()));
}
}
}
System.out.println("Répertoire contenant la classe: " + path);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args)
{
new TestLocation();
}
} |