Java 递归打印文件夹中的所有文件,直到达到一定深度

Java 递归打印文件夹中的所有文件,直到达到一定深度,java,file,recursion,directory,Java,File,Recursion,Directory,我希望搜索给定目录中的所有文件/文件夹,搜索到一定深度。这是到目前为止我的代码 import java.io.File; import java.util.Scanner; /* * Michael Woloski - Program Three * * This program allows the user to enter a desired path * then the program will display every file or directory * wit

我希望搜索给定目录中的所有文件/文件夹,搜索到一定深度。这是到目前为止我的代码

import java.io.File;
import java.util.Scanner;

/* 
 * Michael Woloski - Program Three
 * 
 * This program allows the user to enter a desired path
 * then the program will display every file or directory
 * within the specified path. The user will also enter a
 * desired depth, so if the path contains multiple 
 * directories, it will display the files/folders in the sub
 * directory
 */

public class MainClass {

static Scanner sc = new Scanner(System.in);

public static void fileListingMethod( File [] files, int depth )
{
    if( depth == 0 )
    {
        return;
    }
    else
    {
        for( File file : files )
        {
        if( file.isDirectory() )
            {
                System.out.printf( "Parent: %s\n", file.getParent() );
                System.out.printf( "    Directory:  %s\n", file.getName() );
                fileListingMethod( file.listFiles(), depth-- );
            }
            else
            {
                System.out.printf( "        File:       %s\n", file.getName() );
            }
        }
    }
}

public static void main( String [] args )
{
    System.out.printf("Please Enter a Desired Directory: ");
    String g_input = sc.nextLine();

    if( new File( g_input ).isDirectory() )
    {
        System.out.printf( "Please Enter Desired Depth: " );
        int depth = sc.nextInt();
        File [] file = new File( g_input ).listFiles();
        fileListingMethod( file, depth );
    }
    else
    {
        System.out.printf( "The path %s is not a valid entry. Exiting. ", g_input );
        System.exit( 0 );
    }
  }
}
但是,如果用户输入3作为深度,它将扫描目录中前三个文件夹中的所有文件夹/文件


基本上,我希望从一个目录中获取文件/文件夹到所需的深度。

在进行递归调用时,您正在更改深度;您应该只使用depth-1(在不更改的情况下给出所需的值)。

如果用户输入3作为深度,它将扫描前三个文件夹中的所有文件夹/文件。深度是指它将放入多少嵌套文件夹,而不是它将检查多少文件夹。是的,例如,我正在检查我的下载文件夹C:\Users\Name\downloads,我在该目录中有4个文件夹,如果我输入3,实际上,4个文件夹中只有3个被循环,当它们循环时,它们会显示文件夹中的每个文件或子文件夹,并继续显示,直到最终文件打印出来。谢谢,这很有效,但是,depth——与depth-1相同,不是因为每次迭代都要将变量递减一次吗?但是您希望为同一目录的所有子目录传递相同的值;改变深度是不行的。