ตรวจสอบตำแหน่งของโน้ต
ก่อนเข้าถึงโน้ตที่บันทึกไว้ แอปควรตรวจสอบก่อนว่าไฟล์อยู่ในตำแหน่งที่ถูกต้องหรือไม่ ในแบบฝึกหัดสุดท้ายนี้ คุณจะตรวจสอบว่าไฟล์และโฟลเดอร์ที่ระบุมีอยู่จริงหรือไม่ แล้วพิมพ์ข้อความที่เกี่ยวข้อง เปรียบเหมือนการตรวจสอบชั้นวางก่อนจัดเก็บเอกสาร
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- สร้างออบเจกต์
Fileชื่อnotesDirที่ชี้ไปยังnotes - สร้างไดเรกทอรีใหม่ชื่อ
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());
}
}
}