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