繁体   English   中英

如何在我的Java程序中使用配置文件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM