我想要查找目录和嵌套子目录中的所有
下面的代码在没有任何嵌套子目录的情况下可以正常工作。
问题在于,下面的代码一旦发现嵌套目录,它就只能从该特定嵌套子目录返回文件。 但是我想要在我的目录(父目录和其嵌套子目录)中找到所有的
txt
文件。如果找到了,我想将其从一个位置移动到另一个位置。下面的代码在没有任何嵌套子目录的情况下可以正常工作。
问题在于,下面的代码一旦发现嵌套目录,它就只能从该特定嵌套子目录返回文件。 但是我想要在我的目录(父目录和其嵌套子目录)中找到所有的
txt
文件。public class FilesFindingInDirectory {
static ArrayList<File> al = new ArrayList<File>();
static File fileLocation = null;
public static void main(String[] args) throws IOException {
File filePath = new File("C:\\Users\\Downloads");
File[] listingAllFiles = filePath.listFiles();
ArrayList<File> allFiles = iterateOverFiles(listingAllFiles);
for (File file : allFiles) {
if(file != null) {
String fileName = file.getName();
String sourceFilepath = file.getAbsolutePath();
File targetFilePath = new File("D:\\TestFiles");
String targetPath = targetFilePath.getPath();
Files.move(Paths.get(sourceFilepath), Paths.get("D:\\TestFiles\\" + fileName));
}
}
}
public static ArrayList<File> iterateOverFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
iterateOverFiles(file.listFiles());// Calls same method again.
} else {
fileLocation = findFileswithTxtExtension(file);
if(fileLocation != null) {
System.out.println(fileLocation);
al.add(fileLocation);
}
}
}
return al;
}
public static File findFileswithTxtExtension(File file) {
if(file.getName().toLowerCase().endsWith("txt")) {
return file;
}
return null;
}
}