Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class FilesUtils {
- public static void traverseDirectories(String path) {
- File dir = new File(path);
- File[] allFiles = dir.listFiles();
- if (allFiles == null) {
- return;
- }
- if (allFiles.length == 0) {
- return;
- }
- System.out.println(dir.getName() + ":");
- String indent = "";
- traverseRecursive(allFiles, indent);
- }
- private static void traverseRecursive(File[] list, String indent) {
- if (list == null) return;
- if (list.length == 0) return;
- indent += " ";
- for (File file : list) {
- if (file.isDirectory()) {
- System.out.println(indent + file.getName() + ":");
- traverseRecursive(file.listFiles(), indent);
- }
- if (file.isFile()) {
- System.out.println(indent + file.getName());
- }
- }
- }
- public static List<String> findFiles(String path, String extension) {
- File fileSearch = new File(path);
- File[] allFiles = fileSearch.listFiles();
- List<String> result = new ArrayList<>();
- if (allFiles == null) {
- return result;
- }
- if (allFiles.length == 0) {
- return result;
- }
- for (File file : allFiles) {
- if (file.isDirectory()) {
- result.addAll(findFiles(file.toString(), extension));
- } else {
- if (file.getName().endsWith(extension)) {
- result.add(file.getName());
- }
- }
- }
- return result;
- }
- public static boolean fileExists(String path, String fileName) {
- File dir = new File(path);
- File[] allFilesInDir = dir.listFiles();
- boolean fileNameExist = false;
- if (allFilesInDir == null || allFilesInDir.length == 0) {
- return false;
- }
- for (File file : allFilesInDir) {
- if (file.isDirectory()) {
- fileNameExist = fileExists(file.toString(), fileName);
- }
- if (file.getName().equals(fileName)) {
- return true;
- }
- }
- return fileNameExist;
- }
Advertisement
Add Comment
Please, Sign In to add comment