开始使用免费开始使用

验证笔记位置

在访问已保存的笔记之前,您的应用应先确认它位于正确的位置。在这个最后的练习中,您将检查特定文件和文件夹是否存在,并打印相关信息,就像在归档纸质笔记前先核对书架一样。

本练习是课程的一部分

Java 中的输入/输出与流

查看课程

练习说明

  • 创建一个指向 notesFile 对象 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());
        }
    }
}
编辑并运行代码