Delete all files in directory (but not directory) - one liner solution

前端 未结 11 1368
不思量自难忘°
不思量自难忘° 2020-12-12 11:38

I want to delete all files inside ABC directory.

When I tried with FileUtils.deleteDirectory(new File(\"C:/test/ABC/\")); it also deletes folder ABC.

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 11:48

    Java 8 Stream

    This deletes only files from ABC (sub-directories are untouched):

    Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);
    

    This deletes only files from ABC (and sub-directories):

    Files.walk(Paths.get("C:/test/ABC/"))
                    .filter(Files::isRegularFile)
                    .map(Path::toFile)
                    .forEach(File::delete);
    

    ^ This version requires handling the IOException

提交回复
热议问题