Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เชี่ยวชาญการลบไฟล์ใน Java: คู่มือปฏิบัติจริง

เพื่อลบไฟล์ใน Java เราสามารถใช้เมธอด delete() จาก class Files หรือใช้เมธอด delete() บน object ที่เป็น instance ของ class File

ตัวอย่าง:

การลบไฟล์ด้วย Files Class

ตัวอย่างโค้ดด้านล่างแสดงวิธีลบไฟล์ด้วย class Files:

import java.io.IOException; import java.nio.file.*; public class DeleteFile { public static void main(String[] args) { Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt"); try { Files.delete(path); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); } catch (IOException x) { System.err.println(x); } } }

โค้ดข้างต้นลบไฟล์ชื่อ newFile.txt ใน directory ./src/test/resources/

Multiple catch() blocks จะจับ errors ที่โยนตอนลบไฟล์

การลบไฟล์ด้วย File Class

แทนที่จะใช้ delete() method บน Files class เราสามารถใช้ delete() method บน object ที่เป็น instance ของ File class

ตัวอย่าง:

import java.io.File; public class DeleteFile { public static void main(String[] args) { File myFile = new File("./src/test/resources/newFile.txt"); if (myFile.delete()) { System.out.println("Deleted the file: " + myFile.getName()); } else { System.out.println("Failed to delete the file."); } } }

ลบไฟล์ถ้ามีอยู่

โค้ดต่อไปนี้ใช้เมธอด deleteIfExists() ก่อนลบไฟล์

import java.io.IOException; import java.nio.file.*; public class DeleteFile { public static void main(String[] args) { Path path = FileSystems.getDefault().getPath("./src/test/resources/newFile.txt"); try { Files.deleteIfExists(path); } catch (IOException x) { System.err.println(x); } } }

ในตัวอย่างโค้ดข้างต้น หากไฟล์ไม่มีอยู่ NoSuchFileException จะไม่ถูกโยน

ลบ Directory

เราสามารถใช้โค้ดข้างต้นลบโฟลเดอร์ได้เช่นกัน

หากโฟลเดอร์ไม่ว่าง DirectoryNotEmptyException จะถูกโยน จึงต้อง catch exception นี้อย่างชัดเจน

import java.io.IOException; import java.nio.file.*; public class DeleteFile { public static void main(String[] args) { Path path = FileSystems.getDefault().getPath("./src/test/resources"); try { Files.deleteIfExists(path); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); } catch (DirectoryNotEmptyException x) { System.err.format("%s not empty%n", path); } catch (IOException x) { System.err.println(x); } } }
  • How to create a file in Java
  • How to write to a file in Java