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.