實際開發中若需要讀取配置文件application.properties中的配置,代碼如下。例:讀取配置文件中name屬性配置值:

代碼如下:
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.util.Properties;
public class Test {
/**
* 通過配置文件名讀取內容
* @param fileName
* @return
*/
public static Properties readPropertiesFile(String fileName) {
try {
Resource resource = new ClassPathResource(fileName);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
return props;
} catch (Exception e) {
System.out.println("————讀取配置文件:" + fileName + "出現異常,讀取失敗————");
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Properties properties = readPropertiesFile("application.properties");
System.out.println(properties.getProperty("name"));
}
}
執行結果:

若使用上述方法讀取出現中文亂碼時,說明編碼格式不一致,可使用下面可設置編碼格式方法讀取:
/**
* 通過配置文件名讀取內容
* @param fileName
* @return
*/
public Properties readPropertiesFile(String fileName) {
Properties properties = new Properties();
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream(fileName);
try {
properties.load(new InputStreamReader(inputStream, "UTF-8"));
return properties;
} catch (Exception e) {
logger.info("————讀取配置文件:" + fileName + "出現異常,讀取失敗————");
e.printStackTrace();
}
return null;
}
