如何使用Java I / O在循环中读取文件行?

时间:2016-10-17 18:37:07

标签: java

我正在尝试编写DenverSortedCities并且我确实打印了存在的文件但是我需要编写一个循环来继续阅读,而文件中有更多信息。

当循环遍历文件中的所有城市时,它将跟踪最大城市及其人口。这是我的代码:

my $t=time;
my $tel = new Net::Telnet (Timeout => 2);
eval{
    $tel->open(Host=>$host,Port=>$port) || print "Not OK";
}
my $interval=time-$t;
print "Seconds: $interval";

1 个答案:

答案 0 :(得分:0)

这是一种方法,假设您的文件是CSV文件,其中逗号为分隔符,城市名称为第一个值,其人口为第二个值:

// Use a try-with-resource statement to close the scanner once done
try (Scanner input = new Scanner(inFile)) {
    String largestCity = null;
    int population = 0;
    long total = 0L;
    // Iterate as long as we have remaining lines in the file
    while (input.hasNextLine()) {
        String cityInfo = input.nextLine();
        String[] cityInfoArray = cityInfo.split(",");
        // Convert the second value corresponding to the population to an Integer
        int populationValue = Integer.parseInt(cityInfoArray[1]);
        // Check if the current population is bigger than the current largest
        if (populationValue > population) {
            population = populationValue;
            largestCity = cityInfoArray[0];
        }
        total += populationValue;
    }
    // Print the result
    System.out.printf(
        "The largest city is '%s' with a population of %d inhabitants.%n", 
        largestCity, population
    );
    System.out.printf("The total population is %d.%n", total);
}