我有一个名为Class的文件夹,它的两个子目录是Lectures和Grades,在这两个子目录中是txt文件。如何从主目录-类访问子目录(可能还有“讲义和成绩”子目录的其他子目录)?我知道我可以在代码中使用绝对路径,但是我想从起始文件夹Class开始。到目前为止,我将其作为代码:
public class Test {
public static void main(String[] args) {
File directory = new File("/Users/Desktop/Class");
File[] folder = directory.listFiles();
for (File aFile : folder) {
// Stuck here...
}
}
}
抱歉。我是Java的新手。
答案 0 :(得分:2)
您可以递归调用该方法以读取子目录中的文件
public static void main(String[] args) {
File currentDir = new File("/Users/Desktop/Class"); // current directory
displayDirectoryFiles(currentDir);
}
public static void displayDirectoryFiles(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
正确处理异常,目前仅打印堆栈跟踪
答案 1 :(得分:0)
// Recursive Java program to print all files
// in a folder(and sub-folders)
import java.io.File;
public class GFG
{
static void RecursivePrint(File[] arr,int index,int level)
{
// terminate condition
if(index == arr.length)
return;
// tabs for internal levels
for (int i = 0; i < level; i++)
System.out.print("\t");
// for files
if(arr[index].isFile())
System.out.println(arr[index].getName());
// for sub-directories
else if(arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");
// recursion for sub-directories
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}
// recursion for main directory
RecursivePrint(arr,++index, level);
}
// Driver Method
public static void main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
// File object
File maindir = new File(maindirpath);
if(maindir.exists() && maindir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir
File arr[] = maindir.listFiles();
System.out.println("**********************************************");
System.out.println("Files from main directory : " + maindir);
System.out.println("**********************************************");
// Calling recursive method
RecursivePrint(arr,0,0);
}
}
}
答案 2 :(得分:0)
您是否看过以下答案:Java, List only subdirectories from a directory, not files?
这也可能是一个解决方案,有几种方法:http://zetcode.com/articles/javalistdirectory/
答案 3 :(得分:0)
除了Ros5292答案之外,还可以使用Apache Commons IO
库来实现。
public void iterateFilesAndDirectoriesUsingApacheCommons() {
Iterator it = FileUtils.iterateFilesAndDirs(new File("/Users/Desktop/"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
while (it.hasNext()) {
System.out.println(((File) it.next()).getName());
}
}