[英]How do I utilize a config file with my Java program?
我正在嘗試使用包含主機/網站列表的配置文件以及每個主機/網站的時間頻率。
恩。
google.com 15s
yahoo.com 10s
我的目標是在每個時間段(15秒)從配置文件中ping每個網站。
我應該只讀取配置文件並將主機/時間輸入到單獨的數組中嗎?
似乎有一種更有效的方法......
當兩個項目如此密切相關時,為什么要使用兩個數組?
我把它們放到地圖上:
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>();
pingUrlTimes.put("google.com", 15);
pingUrlTimes.put("yahoo.com", 10);
int pingTime = pingUrlTimes.get("google.com");
以下是如何使用屬性文件的快速概述。
您可以在項目的根目錄中創建擴展名為.properties
的文件(如果在Windows下,請確保顯示文件擴展名)。 屬性可以定義為對:
google.com=15
yahoo.com=10
在Java中
要獲取特定URL的ping時間:
final String path = "config.properties";
Properties prop = new Properties();
int pingTimeGoogle = prop.load(new FileInputStream(path)).getProperty("google.com");
循環瀏覽屬性並獲取整個列表:
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + "=" + props.getProperty(key));
}
編輯:這是將屬性轉換為Map
的一種方便方法(屬性實現Map
接口):
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>((Map) props);
循環遍歷HashMap
可以這樣做:
Iterator iterator = pingUrlTimes.keySet().iterator(); // Get Iterator
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "=" + pingUrlTimes.get(key) );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.