从不同的 .txt 文件获取 INT 并将它们相加

Getting an INT from different .txt files and adding them together

所以我试图从多个 .txt 文件中获取整数,然后将它们相加并将其存储为不同的变量。我已经尝试了一些东西,但除了将一个文本文件存储为一个 int 之外,没有什么能让我更进一步。

声明一个整数(Long 类型)。将其命名为 integersSum.

long integersSum = 0;

将所有文件路径放入一个字符串数组中。

String[] filePaths = {"C:\MyFiles\file1.txt", 
                      "C:\MyFiles\file2.txt",
                      "D:\MyOtherFiles\SomeFile1.txt",
                      "D:\MyOtherFiles\SomeFile2.txt"};

使用循环遍历此数组和 open/read 每个文件。读取每个文件时,提取所有将是字符串的值并将它们转换为整数,但在进行转换之前确保该值使用 String#matches() 方法有效:

long integersSum = 0; // 'long' data type is used in case the integer values in file(s) are quite large.
int actualFilesProcessed = 0;
String ls = System.lineSeparator();

String[] filePaths = {"C:\MyFiles\file1.txt", 
                      "C:\MyFiles\file2.txt",
                      "D:\MyOtherFiles\SomeFile1.txt",
                      "D:\MyOtherFiles\SomeFile2.txt"};

BufferedReader reader;
for (String file : filePaths) {
    try {
        reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim(); // Trim off leading and trailing spaces (if any).

            // Skip lines that are not string representations of a
            // Integer numerical value. The includes blank lines.
            if (!line.matches("\d+")) {
                continue;
            }

            // Add the value with what is already contained within
            // the integersSum variable:
            integersSum += Integer.parseInt(line);
        }
        reader.close();   // Close the current reader.
    }
    catch (FileNotFoundException ex) {
        System.out.println("Can not locate data file! [" + file + "]" 
                           + ls + "Skipping this data file!" + ls);
    }
    catch (IOException ex) {
        System.out.println("I/O Error with file: " + file + ls + ex.getMessage());
    }

    actualFilesProcessed++;  // Increment files processed counter.
} // End of loop

// Display the results in Console.
System.out.println("The total sum of all intger values found within the " 
                 + actualFilesProcessed + " files processed is: " + integersSum);