Get startedGet started for free

Finding local files

You want to write a small program which will print only the local files in a given directory. You have been able to retrieve the list of elements in the directory, stored in DIRECTORY_CONTENT, but :

  • All elements contain first the type, then the element
  • /d means directory,
  • /f means file
  • Some files are hidden, and contain a "."
  • Files in other directors should not be printed Let's fix those now!

This exercise is part of the course

Intermediate Java

View Course

Exercise instructions

  • Use .substring(a,b) and .contains("") to check if the element if file or directory.
  • Check whether a file is hidden when it containsa ".".
  • Check that a file is local by making sure it doesn't contain a "/".
  • Use the correct logical operator to use both conditions at the same time.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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");
  }
}
Edit and Run Code