sunfresh

in class recursion

Jan 21st, 2023
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. public class FilesUtils {
  2.  
  3. public static void traverseDirectories(String path) {
  4. File dir = new File(path);
  5. File[] allFiles = dir.listFiles();
  6. if (allFiles == null) {
  7. return;
  8. }
  9. if (allFiles.length == 0) {
  10. return;
  11. }
  12. System.out.println(dir.getName() + ":");
  13.  
  14. String indent = "";
  15. traverseRecursive(allFiles, indent);
  16. }
  17.  
  18. private static void traverseRecursive(File[] list, String indent) {
  19. if (list == null) return;
  20. if (list.length == 0) return;
  21. indent += " ";
  22. for (File file : list) {
  23. if (file.isDirectory()) {
  24. System.out.println(indent + file.getName() + ":");
  25. traverseRecursive(file.listFiles(), indent);
  26. }
  27. if (file.isFile()) {
  28. System.out.println(indent + file.getName());
  29. }
  30. }
  31. }
  32.  
  33. public static List<String> findFiles(String path, String extension) {
  34. File fileSearch = new File(path);
  35. File[] allFiles = fileSearch.listFiles();
  36. List<String> result = new ArrayList<>();
  37. if (allFiles == null) {
  38. return result;
  39. }
  40. if (allFiles.length == 0) {
  41. return result;
  42. }
  43. for (File file : allFiles) {
  44. if (file.isDirectory()) {
  45. result.addAll(findFiles(file.toString(), extension));
  46. } else {
  47. if (file.getName().endsWith(extension)) {
  48. result.add(file.getName());
  49. }
  50. }
  51. }
  52. return result;
  53. }
  54.  
  55. public static boolean fileExists(String path, String fileName) {
  56. File dir = new File(path);
  57. File[] allFilesInDir = dir.listFiles();
  58. boolean fileNameExist = false;
  59.  
  60. if (allFilesInDir == null || allFilesInDir.length == 0) {
  61. return false;
  62. }
  63. for (File file : allFilesInDir) {
  64. if (file.isDirectory()) {
  65. fileNameExist = fileExists(file.toString(), fileName);
  66. }
  67. if (file.getName().equals(fileName)) {
  68. return true;
  69. }
  70. }
  71. return fileNameExist;
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment