This article describes the method of obtaining the absolute path of a file by JAVA. Share it for your reference. The specific implementation method is as follows:
Copy the code as follows:/**
* Get the absolute path where the class file of a class is located. This class can be a JDK's own class, a user-defined class, or a class in a third-party development package.
* As long as it is a class that can be loaded in this program, it can be located to the absolute path of its class file.
*
* @param cls
* Class attribute of an object
* @return The absolute path to the class file location of this class. If there is no definition for this class, null is returned.
*/
private String getPathFromClass(Class cls) throws IOException {
String path = null;
if (cls == null) {
throw new NullPointerException();
}
URL url = getClassLocationURL(cls);
if (url != null) {
path = url.getPath();
if ("jar".equalsIgnoreCase(url.getProtocol())) {
try {
path = new URL(path).getPath();
}
catch (MalformedURLException e) {
}
int location = path.indexOf("!/");
if (location != -1) {
path = path.substring(0, location);
}
}
File file = new File(path.replaceAll("%20"," "));
path = file.getCanonicalPath();
}
return path;
}
/**
* Get the URL of the class file location. This method is the most basic method of this class and is for other methods to call.
*/
private URL getClassLocationURL(final Class cls) {
if (cls == null) {
throw new IllegalArgumentException("class that input is null");
}
URL result = null;
final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
final ProtectionDomain pd = cls.getProtectionDomain();
if (pd != null) {
final CodeSource cs = pd.getCodeSource();
if (cs != null) {
result = cs.getLocation();
}
if (result != null) {
if ("file".equals(result.getProtocol())) {
try {
if (result.toExternalForm().endsWith(".jar")|| result.toExternalForm().endsWith(".zip")) {
result = new URL("jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
}
else if (new File(result.getFile()).isDirectory()) {
result = new URL(result, clsAsResource);
}
}
catch (MalformedURLException ignore) {
}
}
}
}
if (result == null) {
final ClassLoader clsLoader = cls.getClassLoader();
result = clsLoader != null ? clsLoader.getResource(clsAsResource): ClassLoader.getSystemResource(clsAsResource);
}
return result;
}
I hope this article will be helpful to everyone's Java programming.