【发布时间】: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