This article illustrates how Java obtains the absolute path of a file. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
/**
* Gets the absolute path of the class file for the classes. This class can be the JDK's own class, or it can be a user-defined class, or a class in a third-party development package.
* You can navigate to the absolute path of its class file as long as it is a class that can be loaded in this program.
*
* @param CLS
* The class attribute of an object
* @return The absolute path of the class file location for this category. 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;
}
/**
* Gets the URL of the class file location of the classes. This method is the most basic method of this class for other methods to invoke.
*/
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 = The 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 help you with your Java programming.