0%
题目
- 给定一个文件目录的路径,写一个函数统计这个目录下的所有文件
- 隐藏文件也算,但是文件夹不算
解答
栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public static int getFileNumber(String folderPath) { File root = new File(folderPath); if (!root.isDirectory() && !root.isFile()) { return 0; } if (root.isFile()) { return 1; } Stack<File> stack = new Stack<>(); stack.add(root); int files = 0; while (!stack.isEmpty()) { File folder = stack.pop(); for (File next : folder.listFiles()) { if (next.isFile()) { files++; } if (next.isDirectory()) { stack.push(next); } } } return files; }
|
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| private static int mySolution(String path) { int fileNumber = 0; File file = new File(path); if (!file.exists()) { return 0; } if (file.isFile()) { return 1; } if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { fileNumber = fileNumber + mySolution(f.getPath()); } } return fileNumber; }
|