查找本地文件
您想编写一个小程序,只打印给定目录中的本地文件,而且仅限本地文件。您已经获取了目录中的元素列表,存储在 DIRECTORY_CONTENT 中,但:
- 所有元素都先包含类型,然后是元素本身:
/d表示目录,/f表示文件- 有些文件是隐藏的,包含一个
"." - 其他目录中的文件不应被打印 现在就来修复这些问题吧!
本练习是课程的一部分
Java 中级
练习说明
- 使用
.substring(a,b)和.contains("")来检查元素是文件还是目录。 - 当文件
contains一个"."时,判断该文件为隐藏。 - 通过确保它不包含
"/"来检查文件是否为本地。 - 使用正确的逻辑运算符,同时应用这两个条件。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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");
}
}