始める無料で始める

メモの場所を確認する

保存したメモにアクセスする前に、アプリは想定どおりの場所にあるか確認する必要があります。最後の演習では、特定のファイルやフォルダが存在するかをチェックし、紙のメモを棚にしまう前に棚を確認するのと同じように、状況に応じたメッセージを出力します。

この演習はコースの一部です

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());
        }
    }
}
コードを編集して実行