简体   繁体   English

是否有更清洁/更好的方式来写这个

[英]Would there be a cleaner/better way to write this

The code is suppose to read information from a file, create a object using that information, and then adding it to an ArrayList called servers. 代码是从文件中读取信息,使用该信息创建对象,然后将其添加到名为servers的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();
    }

Example line of what is stored in file: 存储在文件中的示例行:

Name,199.99.99.99,80,60,true

Would there be a better way to retrieve that information to be able to store it in the correct variable without using a loop with a counter the way shown above? 是否有更好的方法来检索该信息,以便能够将其存储在正确的变量中,而无需使用带有计数器的循环,如上所示?

What about: 关于什么:

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);
    }
}

You can just ignore the counter and use directly the tokens, but you should at least be sure there are enough tokens: 您可以忽略计数器并直接使用令牌,但至少应该确保有足够的令牌:

try
{
  BufferedReader br = new BufferedReader(new InputStreamReader());
  String line = null;
  String[] tokens;
  while ((line = br.readLine()) != null) {
     tokens = line.split(",");
     MCServer test = new MCServer(tokens[0],tokens[1],tokens[2],tokens[3],Boolean.valueOf(tokens[4]));
  }
}
catch (IndexOutOfBoundsException e) { // <- be sure to catch this
  // not enough elements in array
}

In addition you are passing strings as IP addresses and port, they are string but they should be checked against being convertible, so you could have Integer.valueOf(tokens[2]) for example just to raise a NumberFormatException in case. 此外,您将字符串作为IP地址和端口传递,它们是字符串,但应检查它们是否可转换,因此您可以使用Integer.valueOf(tokens[2]) ,例如只是为了引发NumberFormatException

Try this 尝试这个

 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;

        String s[] = line.split(",");
        name = s[0];
        ip = s[1];
        port = s[2];
        checkFrequency= s[3];
        alert = s[4];

        MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
        servers.add(server);
    }
    br.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

I've revised your code a bit: 我已经修改了你的代码:

try {
        BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(MainActivity.FILE_SERVERS)));
        String line;
        while ((line = br.readLine()) != null) {

            String[] lineSplitted = line.split(",");

            String name = lineSplitted[0];
            String ip = lineSplitted[1];
            String port = lineSplitted[2];
            String checkFrequency = lineSplitted[3];
            boolean alert = Boolean.parseBoolean(lineSplitted[4]);

            MCServer server = new MCServer(name, ip, port, checkFrequency, alert);
            servers.add(server);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Changes: 变化:

  • initialising the variables and then setting them is redundant, you never access them without setting them beforehand, so if you have your line splitted in the the first place you can initialise them with the values right away 初始化变量然后设置它们是多余的,你不会事先设置它们就可以访问它们,所以如果你先把线分开,你可以立即用值初始化它们。

  • for cycle is unnecessary if you're working with a single array each time, just access the correct elements of the array 如果每次使用单个数组,只需访问数组的正确元素,就不需要循环

  • catch blocks can be collapsed; 捕获块可能会崩溃; IOException covers FileNotFoundException IOException涵盖FileNotFoundException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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