Java 讀取application.properties配置文件中配置


  實際開發中若需要讀取配置文件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;
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM