← Java from Scratch
Lesson 59 of 88 · 10 XP
Deleting files
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
File f = new File("old.txt");
if (f.delete()) // true — deleted, false — it didn't exist or deleting failed
System.out.println("deleted");
delete()deletes a folder too, but only an empty one; to delete a folder with its contents, first delete everything inside (by walking through it, with recursion);Files.delete(path)throws an exception with the reason (NoSuchFileException,DirectoryNotEmptyException), andFiles.deleteIfExists(path)doesn't throw if the file isn't there;- deleting is irreversible: there's no recycle bin.
dir.list() gives the names in a folder, and the order isn't guaranteed — sort them for output.
Task. The program creates the folder box with the files a.txt b.txt c.txt and the folder box/sub with the file
x.txt. Commands: del <path> — delete it and print <path>: deleted or <path>: failed; ls —
print the sorted names in box separated by spaces (if it's empty — (empty)).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.