Cara Mbusak File lan Direktori ing Jawa

Kanggo mbusak file ing Jawa, kita bisa nggunakake delete() cara saka Files kelas. Kita uga bisa nggunakake delete() cara ing obyek sing conto saka File kelas.

Tuladha:



Mbusak File Nggunakake kelas File

Tuladha kode ing ngisor iki nuduhake cara mbusak 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);
}
} }

Kode ing ndhuwur mbusak file sing jenenge newFile.txt ing ./src/test/resources/ direktori

Gunggunge catch() blok bakal nyekel kesalahan sing dibuwang nalika mbusak file kasebut.




Mbusak File Nggunakake Kelas File

Daripada nggunakake delete() cara ing Files klasa, kita uga bisa nggunakake delete() cara ing obyek sing conto saka File kelas.



Tuladha:

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


Mbusak File yen Ana

Kode ing ngisor iki nggunakake deleteIfExists() cara sadurunge mbusak 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);
}
} }

Ing conto kode ing ndhuwur, yen file ora ana, NoSuchFileException ora dibuwang.




Mbusak Direktori

Kita bisa nggunakake kode ing ndhuwur kanggo mbusak folder uga.

Yen folder ora kosong a DirectoryNotEmptyException di buwang, mula kita kudu eksplisit nyekel pengecualian kasebut.

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

Gegandhengan: