MulaiMulai sekarang secara gratis

Memverifikasi lokasi catatan

Sebelum mengakses catatan yang disimpan, aplikasi Anda harus memastikan catatan tersebut berada di lokasi yang semestinya. Pada latihan terakhir ini, Anda akan memeriksa apakah file dan folder tertentu ada, lalu mencetak pesan yang relevan—mirip seperti memeriksa rak sebelum menyimpan catatan kertas.

Latihan ini adalah bagian dari kursus

Input/Output dan Stream di Java

Lihat Kursus

Petunjuk latihan

  • Buat objek File notesDir yang menunjuk ke notes.
  • Buat direktori baru bernama notes.
  • Tampilkan semua isi direktori bernama notes.
  • Ambil path absolut dari file bernama "note.txt".

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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());
        }
    }
}
Edit dan Jalankan Kode