将最近笔记存入缓存
为加快访问最近的笔记,您的应用会把它们存到一个轻量级的缓存文件中。本任务将创建名为 "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());
}
}
}