7

Let's say I want to perform the following operations:

  • List the files in a given directory (as a stream)
  • Map each file (Path) into a Reader (BufferedReader for example) for a consumer to consume.
  • Once a file has been consumed, delete the files

The code would look a bit like this:

Stream<Reader> stream = Files.list(Paths.get("myFolder")) // Returns a stream of Path
  .callback(Files::delete)                                // This would have to be called after the reader has been consumed
  .map(Files::newBufferedReader);                         // Maps every path into a Reader

If I use peek() to delete the files, then the file won't be there when it needs to be mapped into a Reader, so I'd need something that runs after the stream is consumed. Any idea?

3
  • 9
    You don't have to shoehorn everything into streams you know Commented Jan 31, 2019 at 21:00
  • Before you read the file with the associated BufferedReader you could just check if the stream has been deleted with an if-statement. Commented Jan 31, 2019 at 21:01
  • 2
    You can use stream filters and write your delete logic inside the Predicate and return a boolean value to eliminate/keep those files in the stream. Commented Jan 31, 2019 at 21:18

2 Answers 2

12

You can use the DELETE_ON_CLOSE option:

Stream<Reader> stream = Files.list(Paths.get("myFolder"))
        // TODO handle IOException
        .map(path -> Files.newInputStream(path, StandardOpenOption.DELETE_ON_CLOSE))
        .map(InputStreamReader::new)
        .map(BufferedReader::new);
Sign up to request clarification or add additional context in comments.

Comments

0

I went for a slightly different approach in the end. I extended the Reader class and created a wrapper, and I simply overrode the close() method to perform some additional operations on the file (i.e. rename, delete, move etc) once the reader has been consumed.

public class CustomReader extends Reader {
  private Reader reader;
  private File file;

  public CustomReader(File file) {
    this.file = file;
    this.reader = new FileReader(file);
  } 

  [...]
  @Override
  public void close() {
    super.close();
    // Do what you need to do with your file
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.