讀取resources中properties文件內容范例


src/main/resources下test.properties文件內容:(輸入中文文件會自動轉碼)

name=\u674E\u78CA
age=20

src/main/java下ReadProperties.java

package properties;

import java.io.InputStream;
import java.util.Properties;

/**
 * 1 建立Properties對象
 * 2 java反射方式獲取文件的流
 *   getClass():取得當前對象所屬的Class對象
 *   getClassLoader():獲取ReadProperties.class的類加載器
 *   Class.getClassLoader().getResourceAsStream(path): 不在同級目錄下,也不在子目錄下使用這種方法獲取資源,最終是由ClassLoader獲取資源
 * 3 Properties對象加載資源的流
 * 4 使用鍵值對的方式獲取數據
 * 
 * Title: ReadProperties
 *
 * Description: 
 *
 * @author Ethan
 *
 * @date 2019年6月23日
 *
 */

public class ReadProperties {
    public static void main(String[] args) throws Exception {
        //建立Properties對象
        Properties prop = new Properties();
        //獲取文件流
        InputStream ips = ReadProperties.class.getClassLoader().getResourceAsStream("test.properties");
        //加載文件流
        prop.load(ips);
        //獲取數據
        String name = prop.getProperty("name");
        String age = prop.getProperty("age");
        System.out.println(name+":"+age);
    }
}

輸出結果:

李磊:20

 


免責聲明!

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



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