Java obtains the disk location of the file.

Source: Internet
Author: User

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;

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.