Cách xoá file, thư mục trong Java

Trong Java cung cấp một số hàm cho phép chúng ta xoá một file rất đơn giản, tuy nhiên cần lưu ý rằng những file bị xoá này sẽ bị xoá vĩnh viễn mà không được chuyển vào thùng rác như cách thông thường chúng ta xoá trên hệ điều hành.

File.delete()

Bằng cách sử dụng class java.io.File.delete() chúng ta có thể xoá một thư mục hoặc một file bất kỳ thông qua đường dẫn cụ thể đến thư mục, file đó.

import java.io.*; 
  
public class Test 
{ 
    public static void main(String[] args) 
    { 
        File file = new File("C:\\Users\\haitn\\Desktop\\1.txt"); 
          
        if(file.delete()) 
        { 
            System.out.println("File deleted successfully"); 
        } 
        else
        { 
            System.out.println("Failed to delete the file"); 
        } 
    } 
} 

Output: File deleted successfully

Files.deleteIfExists()

Java NIO cũng cung cấp một method cho phép xoá một thư mục hoặc một file nếu nó tồn tại. Cách này có ưu điểm lớn hơn so với cách trên khi nó tự động kiểm tra nếu có sự tồn tại của thư mục, file thì mới tiến hành xoá.

import java.io.IOException; 
import java.nio.file.*; 
  
public class Test 
{ 
    public static void main(String[] args) 
    { 
        try
        { 
            Files.deleteIfExists(Paths.get("C:\\Users\\haitn\\Desktop\\ 
            445.txt")); 
        } 
        catch(NoSuchFileException e) 
        { 
            System.out.println("No such file/directory exists"); 
        } 
        catch(DirectoryNotEmptyException e) 
        { 
            System.out.println("Directory is not empty."); 
        } 
        catch(IOException e) 
        { 
            System.out.println("Invalid permissions."); 
        } 
          
        System.out.println("Deletion successful."); 
    } 
} 

Output: Deletion successful.

Nguồn:

https://www.geeksforgeeks.org/delete-file-using-java/

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x