3

我有一个这样的属性列表,

server1.serverName =""
server1.serverType ="'
server1.hostName =""
server1.userName =""
server1.password =""

在属性文件中,我有“n”个集合,比如

server2, server3,...servern在属性文件中。而且我还有一个类,它包含所有这些元素的getter和setter方法,

public class ServerDetails implements Serializable {

  private String serverName;
  private String serverType;
  private String hostName;
  private String userName;
  private String password;
  ...
}

现在,我需要阅读上面的属性文件并创建一个数组列表,例如,

ArrayList<ServerDetails> serverDetailsList = new ArrayList<ServerDetails>();

其中arrayList 的每个元素都应该有一个ServerDetails 类的对象。我需要知道如何读取属性文件并获取服务器详细信息,以便我可以创建一个对象并将其添加到列表中。

这似乎很容易,但我迷路了。请帮忙。

谢谢 !!

问候, 巴拉

4

4 回答 4

1
  1. 使用 Java IO 打开文件
  2. 逐行解析文件。尝试将“键”“值”对存储在 hashMap 中,然后您可以迭代存储在 arrayList 中的添加/更新 serverDetails。
于 2013-09-23T16:30:20.237 回答
1

您可以将属性文件加载到Properties对象中,然后像这样遍历属性:

int i = 1;
while( properties.get( "server" + i + ".serverName" ) != null ) {
    ServerDetails details = new ...
    details.setServerName( properties.get( [as above] ) );
    ...
    list.add( details );
    ++i;
}
于 2013-09-23T16:31:50.733 回答
0

快速示例:

private static final String KEY ="server";
public static void main(String[] args) throws IOException {
    Properties properties = new Properties();
    properties.load(new FileInputStream("props.properties"));
    int i = 1;
    while (properties.containsKey(KEY + i + ".serverName")) {
        String serverName = properties.getProperty(KEY + i + ".serverName");
        String serverType = properties.getProperty(KEY + i + ".serverType");
        String hostName = properties.getProperty(KEY + i + ".hostName");
        String userName = properties.getProperty(KEY + i + ".userName");
        String password = properties.getProperty(KEY + i + ".password");
        System.out.println(serverName);
        System.out.println(serverType);
        System.out.println(hostName);
        System.out.println(userName);
        System.out.println(password);
        i++;
    }

}

道具.属性:

 server1.serverName =1
 server1.serverType =2
 server1.hostName =3
 server1.userName =4
 server1.password =5

 server2.serverName =6
 server2.serverType =7
 server2.hostName =8
 server2.userName =9
 server2.password =10
于 2013-09-23T16:34:40.353 回答
0
Properties properties = new Properties();
properties.load(new FileInputStream("application.properties"));
int i = 1;
String serverNameKey = "server" + i + ".serverName";

while (properties.containsKey(serverNameKey)) {
    String serverName = (String) properties.get(serverNameKey);
            //Read other properties
    // Create new ServerDetails
    // Add to list
    i++;
}
于 2013-09-23T16:35:21.363 回答