將最近的筆記存到快取
為了加快讀取最近的筆記,你的應用程式會把它們存到輕量的快取檔案中。這個任務中,你將建立一個名為 "cache.txt" 的新檔案,並確認它已成功建立。這會為之後儲存常用資料打好基礎。
java.io 中所需的套件都已經替你匯入。
本練習屬於課程
Java 的輸入/輸出與串流
練習說明
- 建立
"cache.txt"的File物件。 - 檢查該檔案是否已存在。
- 若檔案已存在,將其刪除。
- 建立名為
"cache.txt"的新檔案。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class CacheDataManager {
public static void main(String[] args) {
try {
// Create a File object
File cacheFile = ____ ____("cache.txt");
// Check if the file exists
if (____.____()) {
// Attempt to delete the file
if (____.____()) {
System.out.println("Old cache file deleted successfully.");
} else {
System.out.println("Failed to delete the old cache file.");
}
}
// Create the file for cache.txt
if (____.____()) {
System.out.println("New cache file created successfully.");
} else {
System.out.println("Failed to create the new cache file.");
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}