Hello! There is a task: to write a program that counts the number of files (files and directories) in this directory and in all contained subdirectories using recursion. There is the following stream of consciousness:

import java.io.*; public class Testament { public static void main(String[] args) { FileFly file = new FileFly(); System.out.println(file.fileFly("c:/chocho/")); } } class FileFly { private File file; private File[] s ; private int c = 0; public int fileFly(String path) { file = new File(path); s = file.listFiles(); for(int j=0;j<s.length;j++) { c++; if(s[j].isDirectory()) fileFly(s[j].getPath()); } return c; } } 

This is where it stopped. Help with good advice. How to finish this code to work as it should? Thank you in advance.

    3 answers 3

    You almost completed the work yourself, only the class fields should be members of the method.

     class FileFly { private int c = 0; public int fileFly(String path) { File file = new File(path); File[] s = file.listFiles(); for (int j = 0; j < s.length; j++) { if(!s[j].isDirectory()) c++; if (s[j].isDirectory()) recursionSearc(s[j].getPath()); } return c; } 

    }

    • I modified your version of the code a bit and it all worked. Thank you. - burningsky

    Here is a piece of my old code, it is not quite for counting files and directories, but for printing the tree of this directory! But I think it’s not difficult to remake for your case:

     import java.util.*; import java.io.*; public class File_Directory { //main procedure public static void main (String[] arg){ Scanner scanner=new Scanner (System.in); System.out.println("Enter directory: "); String Path=scanner.nextLine(); printTreeFiles(Path); } public static void printTreeFiles(String Path){ File Directory = new File (Path); if (Directory.exists()){ getContent(Directory,0); } else System.out.println("Directory is not found..."); } //recursive procedure for finding the contents of a directory public static void getContent(File Directory,int Indents) { for (int i=0;i<Indents;i++) System.out.print("\t"); if (Directory.isFile()) System.out.println(Directory.getName()); else { System.out.println(Directory.getName()); File[] SubDirectory = Directory.listFiles(); for (File SubWay:SubDirectory) getContent(SubWay,Indents+1); } } } 
    • Thank. I studied your code, something I learned for myself. - burningsky

    It is necessary to write a method that checks the contents of the folder and would call itself if there was another folder in the contents and so on to infinity. For example:

     public void searchFile(File dir) throws IOException { if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) searchFile(file); } for (File file : files) { int n=0; if (file.isFile()) { //проверяем, файл ли это n++; System.out.println("Файл номер "+n+" найден в " + file.getAbsolutePath());