java maven项目如何读取配置文件信息

这篇文章主要介绍了java maven项目如何读取配置文件信息,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

maven项目读取配置文件信息

目录结构

主类

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; /** * 读取配置文件 * @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); } }

配置文件

jdbc.properties

 jdbc.url=jdbc:mysql://10.6.52.35:3306/test?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false jdbc.driver=com.mysql.jdbc.Driver

pom文件

   4.0.0com.tomy.hivehive-demo1.0-SNAPSHOThive-demohttp://www.example.com UTF-81.81.8  junitjunit4.11test   org.apache.maven.pluginsmaven-surefire-plugin true org.apache.maven.pluginsmaven-jar-plugin3.0.2   truecom.tomy.hive.App maven-resources-plugin  copy-resourcesvalidate copy-resources ${project.build.directory}/conf  src/main/resources  truesrc/main/resources **/**.properties/resources

控制台运行

jar命令运行

maven工程读取resources配置文件的姿势

maven项目结构如下

在这里插入图片描述

使用相对路径来读取resources目录下的资源文件

 InputStream in = new InputStream(new File(“src/main/resources/car.txt”)); 

这样在本地运行的时候,是能正常读取到的,不会报错,但是如果打成jar包,运行的时候就会报路径错误。

从jar包的结构可以看到,resources目录的资源文件位置变了,在项目的最外层了,所以导致相对路径也发生了变化。

在这里插入图片描述

这个时候,我们可以通过getClassLoader()方法来获取正确的配置文件路径。

(this也可以换成类的名称)

 InputStream in = this.class.getClassLoader().getResourceAsStream(path); 

这样,在本地运行或者jar包运行都能正常读取到配置文件了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。

以上就是java maven项目如何读取配置文件信息的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java