java - 从不同的 .txt 文件获取 INT 并将它们加在一起

标签 java file int

所以我试图从多个 .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"};

使用循环,迭代此数组并打开/读取每个文件。读取每个文件时,提取所有将是字符串的值并将其转换为整数,但确保该值与 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);

关于java - 从不同的 .txt 文件获取 INT 并将它们加在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340999/

相关文章:

java - 将 null 值保存为多个键,其中 null 具有单一含义

java - jaxb 解码器将值读取为 0

java - CAS登录-webflow修改添加检票时查看

python - Python 上的 Int 与 Double

c - int 变量的大小

java - 一次从 .txt 获取 16 个字节

java - 如何将文本写入文件而不等待文件关闭

file - 如何将SVG动画文件与音频文件同步?

c - 为什么文本文件中会出现多余的字符?

c - 尝试返回 int 数组时返回错误 "address of stack memory associated with local variable ' processList'