The path of the configuration file cannot be obtained after the jar package is created for the project.

Source: Internet
Author: User
The path of the configuration file cannot be obtained after the jar package is created for the project.

 

Today, I am working on a Java project in development. I want to read the information in the configuration file. when the project is packaged with a jar package, the configuration file cannot be found. The problem is finally solved and I will share it with you.

Method 1: getresource (this method is useful in the war package, but not in the jar package ):
Public static void main (string [] ARGs) {string Path = app. class. getclassloader (). getresource ("config. properties "). getpath (); system. err. println (PATH); file = new file (PATH); If (! File. exists () {system. out. print ("config. the properties file does not exist ");} else {system. err. println ("absolute path:" + file. getabsolutepath ());}}
========================================================== ============================
Result:

/D:/git/practice/Kafka-practice/target/classes/config. Properties
Absolute path: D: \ git \ practice \ Kafka-practice \ target \ Classes \ config. Properties

Method 2: getresourceasstream (required for jar packages)
Public static void main (string [] ARGs) throws ioexception {inputstream in = app. class. getclass (). getresourceasstream ("/config. properties "); properties prop = new properties (); prop. load (in); system. err. println (PROP );}
========================================================== ==============
Result:

{Metadata. Broker. List = cluster1: 9092, compression. codec = 1, Zookeeper. Connect = cluster1: 2181, cluster2: 2181, cluster3: 2181, producer. type = async}

 


The path of the configuration file cannot be obtained after the jar package is created for the project.

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.