Zacznij terazZacznij za darmo

Wyszukiwanie plików lokalnych

Chcesz napisać mały program, który wyświetli tylko pliki lokalne w podanym katalogu. Udało ci się pobrać listę elementów katalogu — jest ona zapisana w DIRECTORY_CONTENT. Pamiętaj jednak, że:

  • Każdy element zawiera najpierw typ, a potem samą nazwę:
  • /d oznacza katalog,
  • /f oznacza plik
  • Niektóre pliki są ukryte i zawierają "."
  • Pliki z innych katalogów nie powinny być wyświetlane Zajmijmy się tym teraz!

To ćwiczenie jest częścią kursu

Java średnio zaawansowany

Zobacz kurs

Instrukcje do ćwiczenia

  • Użyj .substring(a,b) i .contains(""), aby sprawdzić, czy element jest plikiem, czy katalogiem.
  • Sprawdź, czy plik jest ukryty — taki plik contains znak "." w nazwie.
  • Sprawdź, czy plik jest lokalny — upewnij się, że nie zawiera znaku "/".
  • Użyj odpowiedniego operatora logicznego, aby zastosować oba warunki jednocześnie.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

class ls {
  static boolean isFile(String elem) {
    // Check that the first 3 characters of the element contain /f as a substring
    return elem.____(0, 3).____("/f");
  }
  
  static boolean isHidden(String elem) {
    // Use the appropriate method to make sure that file is hidden
    return elem.____(".");
  }

  static boolean isNonLocal(String elem) {
    // Use the correct method to determine whether a file is in a directory
    return elem.____(____, elem.length()).____(____);
  }

  public static void main(String[] args) {
    int hiddenCounter = 0, directoryCounter = 0, nestedCounter = 0;
    for (String elem : DIRECTORY_CONTENT) {
      if (isFile(elem)) {
        if (!isHidden(elem)) System.out.print(elem.substring(2));
          // Use a logical operator to make it correct
        else if (isHidden(elem) ____ !isNonLocal(elem)) hiddenCounter++;
        else nestedCounter++;
      } else directoryCounter++;
    }
    printer(hiddenCounter, directoryCounter, nestedCounter);
  }

  static String[] DIRECTORY_CONTENT = {"/d .Trash", "/f .history", "/d Applications", "/f tmp", "/f script", "/d Documents", "/f Documents/.bankAccounts", "/f .sshKeys", "/d Pictures", "/f content", "/f Documents/file"};

  static void printer(int hiddenCounter, int directoryCounter, int nestedCounter) {
    System.out.println();
    System.out.println("With :\n" + hiddenCounter + " hidden files,\n" + directoryCounter + " directories,\nAnd " + nestedCounter + " nested files");
  }
}
Edytuj i uruchom kod