Nick Melis
Nick Melis

Reputation: 453

Add callback function to Java stream

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

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?

Upvotes: 7

Views: 1919

Answers (2)

Nick Melis
Nick Melis

Reputation: 453

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
  }
}

Upvotes: 0

shmosel
shmosel

Reputation: 50746

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);

Upvotes: 12

Related Questions