Tìm file local
Bạn muốn viết một chương trình nhỏ để in ra chỉ các file local trong một thư mục cho trước. Bạn đã lấy được danh sách phần tử trong thư mục, lưu trong DIRECTORY_CONTENT, nhưng:
- Mỗi phần tử đều bắt đầu bằng kiểu rồi mới đến tên phần tử
/dlà thư mục (directory),/flà tệp (file)- Một số file là ẩn, và có chứa
"." - File ở các thư mục khác không được in ra Hãy xử lý những điểm này nhé!
Bài tập này là một phần của khóa học
Java trung cấp
Hướng dẫn bài tập
- Dùng
.substring(a,b)và.contains("")để kiểm tra phần tử là file hay thư mục. - Kiểm tra một file có ẩn không bằng cách xem nó có
containsmột".". - Kiểm tra một file có local không bằng cách đảm bảo nó không chứa
"/". - Dùng toán tử logic phù hợp để áp dụng cả hai điều kiện cùng lúc.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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");
}
}