Read the file inside the jar while running the jar package

Source: Internet
Author: User

in the development process, we often encounter the situation of reading the configuration file, for the configuration file read, depending on the environment and so on, and so on, in general, if the use of relative/path from a non-jar package, relatively simple, it is not a statement, and in many
case, we need to pack our class into a jar file for use, and then we'll find out that if we hadn't taken that into account before, it might not work, so how do we fix it? Methods are as follows
:
there are the following paths:
web-info--|-->classes--->jdbc.properties
|-->lib
this time addinto what we need to readjdbc.properties, it is a method to read in the following way when the jar package is not used:
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 is processed, the configuration information can be read out, but joined as the class is packaged into a jar file, then, when the program is executed here, will not 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");

Read the file inside the jar while running the jar package

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.