Read the file inside the jar while running the jar package

Source: Internet
Author: User
In the development process, we often encounter reading the configuration file, for the configuration file read, depending on the circumstances, and so on, under normal circumstances, if the use of the relative/path from the jar package, relatively simple, not tired, and in many
case, we need to pack our class into a jar file and use it, and then we'll find that if we didn't take that into account, it might not work, so how do we solve it? Methods are as follows

There are the following paths:
Web-info--|-->classes--->jdbc.properties
|-->lib
At this point we need to read jdbc.properties, and when we do not use the jar package, we read it in the following ways:
File F = new file (This.getclass (). GetResource ("/"). GetPath ());
f = new File (F.getpath () + "/jdbc.properties");
Note: F.getpath () is the absolute path where class is located. such as: c:\javasrc\web-inf\classes
Then, the file object processing, you can read the configuration information, but add as the class is packaged into a jar file, then, when the program is executed here, will not be able to find the configuration file, then how to deal with it.

The processing method is as follows:

Properties Properties=new properties ();

InputStream is = current class name. Class.getclassloader (). getResourceAsStream ("jdbc.properties");

Properties.load (IS);

String Driver = Properties.getproperty ("Jdbc.driverclassname");

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.