How to delete a folder with files using Java

后端 未结 28 3552
北荒
北荒 2020-11-28 05:36

I want to create and delete a directory using Java, but it isn\'t working.

File index = new File(\"/home/Work/Indexer1\");
if (!index.exists()) {
    index.m         


        
28条回答
  •  鱼传尺愫
    2020-11-28 06:04

    2020 here :)

    With Apache commons io FileUtils, contrary to the "pure" Java variants a folder does not need to be empty to be deleted. To give you a better overview I list the variants here, the following 3 may throw exceptions for various reasons:

    • cleanDirectory: Cleans a directory without deleting it
    • forceDelete: Deletes a file. If file is a directory, delete it and all sub-directories
    • forceDeleteOnExit: Schedules a file to be deleted when JVM exits. If file is directory delete it and all sub-directories. Not recommended for running servers as JVM may not exit any time soon ...

    The following variant never throws exceptions (even if the file is null !)

    • deleteQuietly: Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.

    One more thing to know is dealing with symbolic links, it will delete the symbolic link and not the target folder... be careful.

    Also keep in mind that deleting a large file or folder can be a blocking operation for a good while ... so if you do not mind having it run async do it (in a background thread via executor for example).

提交回复
热议问题