Home / Java Patterns and Pitfalls     frequal.com

How to Delete/Move Files from a Stream

Summary

Make sure to .collect() the Paths out of the stream before moving or deleting them, like this:
  stream.collect(Collectors.toList())
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

Details

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 © 2024 Andrew Oliver