When we do Java development (pure Java programs, or Java Web Development), we often encounter the need to read the configuration file, if we write the information about the location of the file directly into the program, for example: e:\workspace\javagui\bin\com\ Util this directory, although feasible, but it has a lot of limitations, because the read file must be satisfied under the e:\workspace\javagui\bin\com\util to be able to read normally, otherwise Java throw exception. If there is no e-disk letter on the server, such a program is not able to execute. So it is necessary for our program to be able to read the location of the current file, thus determining the physical disk location of the file, rather than manually writing to this location.
The following procedure, the implementation of this function
/**
* Gets the path to the class, such as 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 ('/'));
Returns the path to the current class, and handles spaces in the path, because the spaces that appear in the path are not processed, and the
//is disconnected from the space at the time of access, so the complete information is not available, especially in web development.
Return Strurl.replaceall ("%20", "");
} catch (Exception ex) {
Ex.printstacktrace ();
Throw ex;
}
}
Use the following method to get the Superpath, plus your sub-folder below, like 222\444. This save path is best placed under your WebApps, if you use was, it should be placed in the corresponding directory, but not to a certain disk of your machine, and the Web app to walk instead of a fixed letter, you know that your machine may have D, but there is no D disk on the machine, How to create this directory!
String superPath = Tools.getSuperPath()+"222/444/"; if ( (new File(superPath+"/").isDirectory())) { new File(superPath+"/" +foldername).mkdir(); }
Java gets the disk location where the file itself resides