package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteExample {
public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
System.out.println("File to delete: " + path);
System.out.println("File to delete exits: " + Files.exists(path));
//deleting
Files.delete(path);
System.out.println("File exits after deleting: " + Files.exists(path));
}
}
Output
File to delete: C:\Users\Joe\AppData\Local\Temp\test-file17358426713976424126.txt
File to delete exits: true
File exits after deleting: false
Deleting non-existing file will throw exception:
package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DeleteExample2 {
public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
//deleting
Files.delete(path);
//deleting non-exiting file
Files.delete(path);
}
}
Output
Caused by: java.nio.file.NoSuchFileException: C:\Users\Joe\AppData\Local\Temp\test-file1483502319815186337.txt
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:270)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
at java.base/java.nio.file.Files.delete(Files.java:1134)
at com.logicbig.example.files.DeleteExample2.main(DeleteExample2.java:21)
... 6 more