需要在我的代码(java)中稍作修改(计算行数)(初学者)
我的目标是编写一个代码,允许我计算文件夹及其子文件夹中txt文件的行数,我编写了一个代码,允许我只对单个文件执行此操作,我应该更改什么以获得良好的结果?无法在代码中指定目录需要在我的代码(java)中稍作修改(计算行数)(初学者),java,file,Java,File,我的目标是编写一个代码,允许我计算文件夹及其子文件夹中txt文件的行数,我编写了一个代码,允许我只对单个文件执行此操作,我应该更改什么以获得良好的结果?无法在代码中指定目录 import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Lines {
public static String getValueFromUser(String comment) {
Scanner scanner = new Scanner(System.in);
System.out.println(comment);
return scanner.nextLine();
}
public static void main(String[] args) {
String filePath = getValueFromUser("location: ");
readFileContent(filePath);
}
private static void readFileContent(String filePath) {
int numberOfLines = 0;
String textLine;
try (BufferedReader fileReader = new BufferedReader(new FileReader(filePath))) {
while ((textLine = fileReader.readLine()) != null) {
numberOfLines++;
}
System.out.println("number of lines: " + numberOfLines);
} catch (FileNotFoundException ex) {
System.out.println("no file found.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
要计算目录中所有.txt文件的所有行数,您需要迭代该目录及其子目录的内容。使用
文件
类非常简单(如果允许的话):
请注意,这将只打印每个文件的行数。如果需要获取总数,则不应使用
forEach()
,而应使用maptoInt(…).sum()
并从方法中返回行数。是否允许使用文件
类?如果是这样,请查看文件.walk()
(流式传输所有文件路径)或文件.find()
(在流的早期应用过滤器)。好的,forEach方法可以工作,但mapToInt不能,我将readFileContent更改为int,添加了返回语句,但现在该总和的结果被忽略。@user15787568假设您正确返回了numberOfLines
,您是否使用了类似mapToInt(path->readFileContent(path.toString())
?还要注意,这将导致一个IntStream
,因此最后需要一个sum()
——当然,将该方法的结果存储在某个地方并打印出来。
Files.walk(Path.of(filePath )) //iterates through all files and directories in the given locaction
.filter(path -> Files.isRegularFile(path)) //we're only interested in files
.filter(path -> path.toFile().getName().endsWith(".txt")) //specifically those ending in .txt
.forEach(path -> readFileContent(path.toString())); //call your method here