Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add callback function to Java stream

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?

like image 593
Nick Melis Avatar asked Jan 31 '19 20:01

Nick Melis


People also ask

Does Java support callback function?

Memory address of a function is represented as 'function pointer' in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2(). Callback in Java : But the concept of a callback function does not exist in Java because Java doesn't have pointer concept.

What is callback function in Java?

A CallBack Function is a function that is passed into another function as an argument and is expected to execute after some kind of event. The purpose of the callback function is to inform a class Sync/Async if some work in another class is done. This is very useful when working with Asynchronous tasks.

What is callback handler in Java?

An application implements a CallbackHandler and passes it to underlying security services so that they may interact with the application to retrieve specific authentication data, such as usernames and passwords, or to display certain information, such as error and warning messages.


1 Answers

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);
like image 51
shmosel Avatar answered Oct 23 '22 16:10

shmosel