Java recursively reads all files in the directory (including all files in the subdirectory) as follows: use the file.listFiles() method to obtain all files in the directory (including all files in the subdirectory), obtain files[] array, and then traverse all files. Use isFile (file) and isDirectory (folder) methods to determine whether the read file or folder. If the obtained folder is a folder, call the test() method recursively. If the obtained file is a file, add it to the fileList. When the final test is traversed all files in the fileList to verify the accuracy of reading data.
package com.chaoyue.io.test; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Recursively read all files in a directory* * @author Beyond* @Date December 5, 2016, 4:04:59 pm * @motto People are called party, and hearts are called team* @Version 1.0 */ public class ReadFile { private static void test(String fileDir) { List<File> fileList = new ArrayList<File>(); File file = new File(fileDir); File[] files = file.listFiles();// Get all files or folders in the directory if (files == null) {// If the directory is empty, exit the return directly; } // Traversing, all files in the directory for (File f : files) { if (f.isFile()) { fileList.add(f); } else if (f.isDirectory()) { System.out.println(f.getAbsolutePath()); test(f.getAbsolutePath()); } } for (File f1 : fileList) { System.out.println(f1.getName()); } } public static void main(String[] args) { test("F:/apache-tomcat-7.0.57-windows-x64"); } }The file structure in the local directory is as follows
The files in the test read directory are as follows
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.