When running the jar package, read the files in the jar package.

Source: Internet
Author: User

When running the jar package, read the files in the jar package.
During the development process, we often encounter reading configuration files. The reading of configuration files varies depending on the environment. Generally, if relative/path is used from a non-jar package, it is relatively simple and will not be described.
In this case, we need to package our class into a jar file and use it. Then we will find that if we didn't consider this before, it may not work, how can this problem be solved? The method is as follows:
:
The following paths are available:
Web-info -- | --> classes ---> jdbc. properties
| --> Lib
In this case, we need to read jdbc. properties. When we do not use the jar package, we can use the following method to read the data:
File f = new File (this. getClass (). getResource ("/"). getPath ());
F = new File (f. getPath () + "/jdbc. properties ");
Note: f. getPath () is the absolute path where the class is located. For example, c: \ javasrc \ web-inf \ classes
Then, after processing the file object, you can read the configuration information, but add the above class to be packaged into a jar file. Then, when the program is executed here, the configuration file cannot be found. How can this problem be solved?

The solution 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.