Home / Java Patterns and Pitfalls     frequal.com

How to Delete/Move Files from a Stream


Make sure to .collect() the Paths out of the stream before moving or deleting them, like this:
If you don't, you will encounter errors like this:
java.nio.file.FileAlreadyExistsException: /home/username/path/to/file
or this:
java.io.UncheckedIOException: java.nio.file.NoSuchFileException: /home/username/path/to/file


Sometimes you have a stream of files to process (like from Files.find()). While a convenient method, the Paths in the resulting stream can't be deleted while iterating over the stream. To do so results in the exceptions above.

First, collect the Stream into a List:

  List<Path> listPaths = stream.collect(Collectors.toList())
Then use a foreach loop to process the Paths:
 for (Path path : listPaths) {

Last modified on 31 Dec 2017 by AO

Copyright © 2020 Andrew Oliver