假定代码从文件中读取信息,使用该信息创建对象,然后将其添加到称为服务器的ArrayList中。

    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
        String line = "";
        while ((line = br.readLine()) != null) {
            String name = "";
            String ip = "";
            String port = "";
            String checkFrequency = "";
            int counter = 1;
            boolean alert = true;
            for (String value : line.split(",")){
                if (counter == 1){
                    name = value;
                }else if (counter == 2){
                    ip = value;
                }else if (counter == 3){
                    port = value;
                }else if (counter == 4){
                    checkFrequency = value;
                }else if (counter == 5){
                    alert = Boolean.parseBoolean(value);
                }
                counter++;
            }
            MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
            servers.add(server);
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


存储在文件中的示例行:

Name,199.99.99.99,80,60,true


是否有更好的方法来检索该信息,以便能够将其存储在正确的变量中,而无需使用带有计数器的循环(如上所示)?

最佳答案

关于什么:

try (BufferedReader br = new BufferedReader(
       new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)))) {
    String line = null;  // start with null in case there is no line
    while ((line = br.readLine()) != null) {
        String[] tokens = line.split(",");
        MCServer server =
            new MCServer(tokens[0], tokens[1], tokens[2], tokens[3],
              Boolean.parseBoolean(tokens[4]));
        servers.add(server);
    }
}

09-10 22:55