在項目中我們經常會需要讀一些配置文件來獲取配置信息,然而對於這些配置文件在項目中存放的位置以及獲取這些配置文件的存放路徑卻經常搞不清楚,自己研究了一下,記錄下來以備后用。
測試代碼如下
package com.example.test.aspect; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; public class Main { public static void main(String[] args) throws Exception{ System.out.println(Main.class.getResource("/application.properties").getPath()); System.out.println(Main.class.getResource("").getPath()); System.out.println(Main.class.getClassLoader().getResource("").getPath()); System.out.println(ResourceUtils.getFile("classpath:application.properties")); File file = new File(Main.class.getClassLoader().getResource("application.properties").getPath()); InputStream inputStream = new FileInputStream(file); Properties properties = new Properties(); properties.load(inputStream); System.out.println(properties.getProperty("sdf")); } }
1、Main.class.getResource("/").getPath()) , 獲取的是項目的類路徑,對於springboot項目resource目錄下的文件編譯后會放在類路徑下
2、Main.class.getResource("").getPath(),獲取的則是當前類Main.classs所在包的路徑
3、Main.class.getClassLoader().getResource("").getPath(),通過類加載器獲取的是項目的類路徑
4、還可以使用spring的工具類利用ResourceUtils.getFile("classpath:application.properties")獲取resource目錄下的配置文件
5、最后借助於jdk properties讀取配置文件中的信息
代碼運行結果如下: