You can delete files, directories or links. With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails.The
Pathclass provides two deletion methods.The
deletemethod deletes the file or throws an exception if the deletion fails. For example, if the file does not exist aNoSuchFileExceptionis thrown. You can catch the exception to determine why the delete failed as follows:try { path.delete(); } 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) { //File permission problems are caught here. System.err.println(x); }The
deleteIfExistsmethod also deletes the file, but if the file does not exist, no exception is thrown. Failing silently is useful when you have multiple threads deleting files and you don't want to throw an exception just because one thread did so first.