gpt4 book ai didi

java - 读取文件的递归方法不起作用

转载 作者:行者123 更新时间:2023-12-01 18:10:55 25 4
gpt4 key购买 nike

我这里有这个方法,我想递归地查找文件夹以计算以“D”开头的文件。

它向我展示了StackOverflowError

public void CountThem() throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();

for(File f : files){
if(f.isDirectory()){
CountThem();
}else{
if(f.getName().startsWith("D")){
count++;
}
}
}
}

最佳答案

这是因为当 File 是一个目录时,您将重新开始您的函数,这会导致无限循环。您必须定义以 File 作为参数的函数:

public int countThem(File file) throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();

for(File f : files){
if(f.isDirectory()) {
count += countThem(f);
} else {
if(f.getName().startsWith("D")) {
count++;
}
}
}

return count;
}

P.S.:在java中,方法名称以小写开头是一个标准。

编辑:

public class Fajlla {

File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}

public int callItOUU() throws IOException{
return this.countThem(folder);
}


public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(file);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}




public static void main(String[] args) {

try {

Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU(new File("C:/Users/Admin/Desktop/dreniii.txt"));
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}

}


}

关于java - 读取文件的递归方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com