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