Kumaha Hapus Payil sareng Diréktori di Java

Pikeun mupus file di Java, urang tiasa nganggo delete() cara ti Files kelas. Kami ogé tiasa nganggo delete() metoda dina obyék anu conto tina File kelas.

Conto:

Ngahapus File Nganggo kelas Files

Conto kode di handap nunjukkeun kumaha ngahapus file nganggo Files kelas:

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

Kodeu di luhur ngahapus file anu namina newFile.txt di ./src/test/resources/ diréktori.

Ganda catch() blok bakal néwak kasalahan naon waé anu dialungkeun nalika ngahapus file ieu.

Ngahapus File Nganggo Kelas File

Daripada nganggo delete() cara dina Files kelas, urang ogé tiasa nganggo delete() metoda dina obyék anu conto tina File kelas.



Conto:

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

Hapus File upami Ayana

Kodeu ieu nganggo deleteIfExists() metoda sateuacan mupus 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);
}
} }

Dina conto kode di luhur, upami file henteu aya, NoSuchFileException henteu dialungkeun.

Hapus Diréktori a

Urang tiasa nganggo kode di luhur pikeun ngahapus folder ogé.

Upami folder henteu kosong a DirectoryNotEmptyException dialungkeun, janten urang kedah jelas-jelas néwak pengecualianna.

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

Patali: