1. 程式人生 > >使用Properties物件獲取.properties配置檔案中的值

使用Properties物件獲取.properties配置檔案中的值

1.在專案中新建一個constant.propertis檔案,並設定username=root

2.建立一個java類,程式碼如下:

public class ConstantUtil {


private static Properties p = new Properties();

static {

InputStream inputStream = ConstantUtil.class.getClassLoader().getResourceAsStream

                ("constant.properties");   

try {   
p.load(inputStream);   
} catch (IOException e1) {   
e1.printStackTrace();  
}   

}

        public static String USER_NAME= p.getProperty("username");

}

3,建立測試類

public class Test(){

    public static void main(String[] args){

           System.out.println(ConstantUtil.USER_NAME);

    }

}