實際開發中若須要讀取配置文件application.properties中的配置,代碼以下。例:讀取配置文件中name屬性配置值:java
代碼以下:spring
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")); } }
執行結果:app
若使用上述方法讀取出現中文亂碼時,說明編碼格式不一致,可以使用下面可設置編碼格式方法讀取:編碼
/** * 經過配置文件名讀取內容 * @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; }