递归读取文件夹下的文件,代码怎么实现
=================================记录Start==================================
这个问题就是在考验你递归,让你写个递归方法出来。也只有递归才能这么解决问题。
具体实现如下:
- /**
- * 递归读取文件夹下的 所有文件
- *
- * @param testFileDir 文件名或目录名
- */
- private static void testLoopOutAllFileName(String testFileDir) {
- if (testFileDir == null) {
- //因为new File(null)会空指针异常,所以要判断下
- return;
- }
- File[] testFile = new File(testFileDir).listFiles();
- if (testFile == null) {
- return;
- }
- for (File file : testFile) {
- if (file.isFile()) {
- System.out.println(file.getName());
- } else if (file.isDirectory()) {
- System.out.println("-------this is a directory, and its files are as follows:-------");
- testLoopOutAllFileName(file.getPath());
- } else {
- System.out.println("文件读入有误!");
- }
- }
- }
如上图的测试结果,以及测试代码传入的目录。
如下方法调用上述方法:
testLoopOutAllFileName("F:/桌面文件");
=================================记录End==================================