Computer >> Máy Tính >  >> Lập trình >> Java

Cách xóa tệp và thư mục trong Java

Để xóa một tệp trong Java, chúng ta có thể sử dụng delete() phương thức từ Files lớp. Chúng tôi cũng có thể sử dụng delete() trên một đối tượng là một phiên bản của Files lớp học.

Ví dụ:

Xóa tệp bằng lớp Tệp

Ví dụ mã bên dưới cho thấy cách xóa tệp bằng Files lớp:

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);
        }
    }
}

Đoạn mã trên xóa một tệp có tên newFile.txt trong ./src/test/resources/ thư mục.

Nhiều catch() các khối sẽ bắt gặp bất kỳ lỗi nào được tạo ra khi xóa tệp.

Xóa tệp bằng lớp tệp

Thay vì sử dụng delete() trên Files , chúng ta cũng có thể sử dụng delete() trên một đối tượng là một phiên bản của Files lớp học.

Ví dụ:

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.");
        }
    }
}

Xóa tệp nếu tồn tại

Đoạn mã sau sử dụng deleteIfExists() trước khi xóa tệp.

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);
        }
    }
}

Trong ví dụ mã trên, nếu tệp không tồn tại, NoSuchFileException không bị ném.

Xóa thư mục

Chúng tôi cũng có thể sử dụng mã trên để xóa một thư mục.

Nếu thư mục không trống, một DirectoryNotEmptyException được ném ra, vì vậy chúng tôi phải bắt ngoại lệ một cách rõ ràng.

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);
        }
    }
}

Có liên quan:

  • Cách tạo tệp trong Java
  • Cách ghi vào một tệp trong Java