We are developing Java (pure JavaProgramOr Java Web development), we often encounter the need to read the configuration file, if we directly write the information of the file location to the program, such as: e: although this directory \ workspace \ javagui \ bin \ com \ util is feasible, it imposes great limitations because the file to be read must meet the requirements in E: \ workspace \ javagui \ bin \ com \ util can be read normally; otherwise, an exception is thrown in Java. If such a program cannot be executed on a server without an e drive letter. Therefore, our program needs to be able to read the location of the current file to determine the location of the physical disk of the file, rather than manually writing to this location.
The following program implements this function
/**
* Obtain the class path, for example, E: \ workspace \ javagui \ bin \ com \ util.
* @ Return
* @ Throws java. Lang. Exception
*/
Public String getclasspath () throws exception {
Try {
String strclassname = getclass (). getname ();
String strpackagename = "";
If (getclass (). getpackage ()! = NULL ){
Strpackagename = getclass (). getpackage (). getname ();
}
String strclassfilename = "";
If (! "". Equals (strpackagename )){
Strclassfilename = strclassname. substring (strpackagename. Length () + 1,
Strclassname. Length ());
} Else {
Strclassfilename = strclassname;
}
URL url = NULL;
Url = getclass (). getresource (strclassfilename + ". Class ");
String strurl = URL. tostring ();
Strurl = strurl. substring (strurl. indexof ('/') + 1, strurl
. Lastindexof ('/'));
// Return the path of the current class and process the space in the path, because if the space in the path is not processed,
// The space will be disconnected during access, so the complete information will not be obtained. This issue should be particularly noted in Web development.
Return strurl. replaceall ("% 20 ","");
} Catch (exception ex ){
Ex. printstacktrace ();
Throw ex;
}
}