Để xóa file trong Java, chúng ta có thể dùng phương thức delete() từ class Files. Chúng ta cũng có thể dùng phương thức delete() trên một object là instance của class File.
Ví dụ:
Xóa File Dùng Class Files
Ví dụ code dưới đây chỉ cách xóa file với 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);
}
}
}
Code trên xóa file tên newFile.txt trong thư mục ./src/test/resources/.
Nhiều block catch() sẽ bắt bất kỳ lỗi nào ném ra khi xóa file.
Xóa File Dùng Class File
Thay vì dùng phương thức delete() trên class Files, chúng ta cũng có thể dùng phương thức delete() trên object là instance của class File.
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 File Nếu Tồn Tại
Code sau dùng phương thức deleteIfExists() trước khi xóa file.
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ụ code trên, nếu file không tồn tại, NoSuchFileException không được ném.
Xóa Thư Mục
Chúng ta có thể dùng code trên để xóa thư mục cũng được.
Nếu thư mục không rỗng, DirectoryNotEmptyException được ném, nên chúng ta phải bắt exception đó 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ách tạo file trong Java
- Cách ghi file trong Java