Given a folder in the actual project, there is not much need to get all the files in this folder, more to find or delete a specific file
Import Java.io.File;
Import java.util.ArrayList;
public class Filetest {
private static arraylist<string> filelist = new arraylist<string> ();
public static void Main (string[] args) throws Exception {
String FilePath = "D:/xinxi";
GetFiles (FilePath);
}
/*
* Recursively get all the directories and their files under a certain path
*/
static void GetFiles (String filePath) {
File root = new file (FilePath);
file[] files = root.listfiles ();
for (File file:files) {
if (File.isdirectory ()) {
/*
* Recursive call
*/
GetFiles (File.getabsolutepath ());
Filelist.add (File.getabsolutepath ());
System.out.println ("Show" +filepath+ "all subdirectories and their files" +file.getabsolutepath ());
}else{
System.out.println ("Show" +filepath+ "All Subdirectories" +file.getabsolutepath ());
}
}
}
}
1. Method calls that do not use recursion.
public void TraverseFolder1 (String path) {
int filenum = 0, foldernum = 0;
File File = new file (path);
if (file.exists ()) {
linkedlist<file> list = new linkedlist<file> ();
file[] files = file.listfiles ();
for (File file2:files) {
if (File2.isdirectory ()) {
System.out.println ("folder:" + File2.getabsolutepath ());
List.add (file2);
filenum++;
} else {
System.out.println ("File:" + File2.getabsolutepath ());
foldernum++;
}
}
File Temp_file;
while (!list.isempty ()) {
Temp_file = List.removefirst ();
Files = Temp_file.listfiles ();
for (File file2:files) {
if (File2.isdirectory ()) {
System.out.println ("folder:" + File2.getabsolutepath ());
List.add (file2);
filenum++;
} else {
System.out.println ("File:" + File2.getabsolutepath ());
foldernum++;
}
}
}
} else {
SYSTEM.OUT.PRINTLN ("file does not exist!");
}
System.out.println ("folder total:" + Foldernum +), a total of files: "+ FileNum);
}
Called using recursive method.
public void TraverseFolder2 (String path) {
File File = new file (path);
if (file.exists ()) {
file[] files = file.listfiles ();
if (Files.length = = 0) {
System.out.println ("folder is empty!");
Return
} else {
for (File file2:files) {
if (File2.isdirectory ()) {
System.out.println ("folder:" + File2.getabsolutepath ());
TraverseFolder2 (File2.getabsolutepath ());
} else {
System.out.println ("File:" + File2.getabsolutepath ());
}
}
}
} else {
SYSTEM.OUT.PRINTLN ("file does not exist!");
}
}