【问题标题】:Recursively printing all files in a folder up to a certain depth递归打印文件夹中的所有文件到一定深度
【发布时间】:2013-12-27 08:22:43
【问题描述】:

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

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

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

【问题讨论】:

  • if the user inputs 3 as the depth it scans all the folder/files within the first three folders。深度意味着它会关闭多少个嵌套文件夹,而不是它会检查多少个文件夹。
  • 是的,例如我正在检查我的下载文件夹 C:\Users\Name\Downloads 并且我在该目录中有 4 个文件夹,如果我输入 3,则 4 个文件夹中只有 3 个实际上被循环当他们这样做时,他们会显示文件夹中的每个文件或子文件夹并继续直到打印最终文件。

标签: java file recursion directory


【解决方案1】:

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

【讨论】:

  • 谢谢,这行得通,但不是深度 - 与 depth-1 相同,因为您每次迭代都会减少一次变量?
  • 但是你想为同一目录的所有子目录传递相同的值;改变深度不会那样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 2016-10-25
  • 2016-12-19
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2013-11-22
相关资源
最近更新 更多