驗證筆記位置
在存取已儲存的筆記之前,你的應用程式應該先確認它是否在正確的位置。在這個最後的練習中,你將檢查特定檔案與資料夾是否存在,並印出相關訊息,就像在歸檔紙本筆記前先核對櫃位一樣。
本練習屬於課程
Java 的輸入/輸出與串流
練習說明
- 建立一個指向
notes的File物件notesDir。 - 建立一個名為
notes的新目錄。 - 列出名為
notes的目錄中所有內容。 - 取得名為
"note.txt"檔案的絕對路徑。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class DirectoryManager {
public static void main(String[] args) {
try {
// Create a directory
File notesDir = ____ ____("notes");
if (____.____()) {
System.out.println("Directory 'notes' created successfully");
}
File noteFile = new File("notes/note.txt");
if (noteFile.createNewFile()) {
System.out.println("File 'note.txt' created successfully");
}
// List contents of the directory
File[] files = ____.____();
if (files != null) {
for (File f : files) {
System.out.println("File: " + f.getName());
}
}
// Retrieve and print the absolute path of the file
System.out.println("Absolute Path: " + ____.____());
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}