How does a java maven project read configuration file information
This article is about how java maven projects read configuration file information. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Maven project read profile information
Directory structure
Main class
App.java
Package com.tomy.hive; import java.io.*;import java.util.Properties; / * Hello world! * * / public class App {private static String JDBC_URL; private static String JDBC_DRIVER; / * read configuration file * @ return * / public static void readConfigFile (String cfgFile) {try {InputStream in = App.class.getClassLoader () .getResource (cfgFile) .openStream () Properties prop = new Properties (); prop.load (in); JDBC_URL = prop.getProperty ("jdbc.url"); JDBC_DRIVER = prop.getProperty ("jdbc.driver");} catch (IOException e) {e.printStackTrace ();}} public static void main (String [] args) {readConfigFile ("resources/jdbc.properties") System.out.println (JDBC_URL); System.out.println (JDBC_DRIVER);}} configuration file
Jdbc.properties
Jdbc.url=jdbc:mysql://10.6.52.35:3306/test?characterEncoding=utf-8&serverTimezone=UTC&useSSL=falsejdbc.driver=com.mysql.jdbc.Driverpom file 4.0.0 com.tomy.hive hive-demo 1.0-SNAPSHOT hive-demo http://www.example.com UTF-8 1.81.8 junit junit 4.11 test Org.apache.maven.plugins maven-surefire-plugin true org.apache.maven.plugins maven-jar-plugin 3.0.2 true com. Tomy.hive.App maven-resources-plugin copy-resources validate copy-resources ${project.build.directory} / Conf src/main/resources true src/main/resources * * / * * .properties / resources console runs
The jar command runs
Maven project reads the correct posture of the resources configuration file
The structure of our maven project is as follows:
Use relative paths to read resource files in the resources directory
InputStream in = new InputStream (new File ("src/main/resources/car.txt"))
In this way, when running locally, it can be read normally and will not report an error, but if it is typed into a jar package, the path error will be reported at run time.
As you can see from the structure of the jar package, the location of the resource files in the resources directory has changed, at the outermost layer of the project, resulting in a change in the relative path.
At this point, we can get the correct configuration file path through the getClassLoader () method.
(this can also be changed to the name of the class)
InputStream in = this.class.getClassLoader () .getResourceAsStream (path)
In this way, the configuration file can be read normally either locally or by running the jar package.
Thank you for reading! This is the end of this article on "how to read configuration file information for java maven projects". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!