递归打印文件夹中的所有文件,直到某个深度

时间:2013-12-10 00:49:06

标签: 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
 * 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作为深度,则会扫描目录中前三个文件夹中的所有文件夹/文件。

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

1 个答案:

答案 0 :(得分:0)

你正在改变递归呼叫的深度;你应该只使用depth-1(给出你想要的值而不改变它)。