给定一个文件夹地址输出该文件夹下所有文件
1.递归方式遍历文件夹:
package file; import java.io.File; import java.util.Scanner; /** * 递归遍历文件夹 * 若输入的为文件,则直接输出该文件名,输入的为文件夹,则输出其中的所有文件 * @author Administrator * */ public class TraverseFolderByRecursion { public static void traverseFolder(String path, int fileLevel) { File file = new File(path); // int fileNum =0; /** 判断文件是否存在 */ if (file.exists()) { /** 判断获取的为文件还是文件夹 */ if (file.isDirectory()) { File[] fileName = file.listFiles(); /** 文件夹是否为空,不为空则遍历 */ if (null == fileName || fileName.length == 0) { if (fileLevel == 0) { System.out.println("该文件夹为空!"); } } else { fileLevel++; for (File f : fileName) { System.out.println(f.getName()); traverseFolder(f.getAbsolutePath(), fileLevel); } } } else { if (fileLevel == 0) { System.out.println(file.getName()); } } } else { System.out.println("该文件或文件夹不存在!"); } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); String path = scanner.nextLine(); // System.out.println("所有文件及文件夹:"); traverseFolder(path, 0); } }
2.利用栈遍历文件夹:
package file; import java.io.File; import java.util.Scanner; import java.util.Stack; /** * 利用栈遍历文件夹 * 若输入的为文件,则直接输出该文件名,输入的为文件夹,则输出其中的所有文件 * @author Administrator path:文件或文件夹路径 fileLevel:目录层级,输入的默认层级为第0层 * */ public class TraverseFolderByStack { public static void traverseFolder(String path, int fileLevel) { File dir = new File(path); if (!dir.isDirectory()) { System.out.println(dir.getName()); } else { if (dir.exists()) { Stack<File> stack = new Stack(); /** 一级目录入栈 */ stack.push(dir); File file = null; /** 栈不为空时 */ while (stack.size() > 0) { /** 获取栈顶元素值并将其移除 */ if (fileLevel == 0) { /** 第0层即输入的文件夹目录直接出栈 */ file = stack.pop(); } else { /** 非第0层即子目录出栈并输出其文件名 */ file = stack.pop(); System.out.println(file.getName()); } File[] files = file.listFiles(); /**文件夹不为空时*/ if (null != files && files.length > 0) { for (File f : files) { /** 元素为目录即文件夹时入栈 */ if (f.isDirectory()) { stack.push(f); fileLevel++; } else { /** 元素为文件时直接输出 */ System.out.println(f.getName()); fileLevel++; } } } } /** 输入的目录为空时 */ if (fileLevel == 0) { System.out.println("该文件夹为空!"); } } else { System.out.println("该文件或文件夹不存在!"); } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); String path = scanner.nextLine(); // System.out.println("所有文件及文件夹:"); traverseFolder(path, 0); } }
原文:https://www.cnblogs.com/lingFeimao/p/10711769.html