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

前端 未结 11 1364
不思量自难忘°
不思量自难忘° 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

    Or to use this in Java 8:

    try {
      Files.newDirectoryStream( directory ).forEach( file -> {
        try { Files.delete( file ); }
        catch ( IOException e ) { throw new UncheckedIOException(e); }
      } );
    }
    catch ( IOException e ) {
      e.printStackTrace();
    }
    

    It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...

提交回复
热议问题