title: Java8 Stream of files, how to control the closing of files?
body: <p>Suppose I have a Java8 <code>Stream&lt;FileReader&gt;</code> and that I use that stream to <code>map</code> and such, how can I control the closing of the <code>FileReader</code>s used in the stream?</p>
  
  <p>Note, that I may not have access to the individual <code>FileReader</code>s, for example:</p>
  
  <pre><code>filenames.map(File::new)
      .filter(File::exists)
      .map(f-&gt;{
          BufferedReader br = null;
          try {
              br = new BufferedReader(new FileReader(f));
          } catch(Exception e) {}
              return Optional.ofNullable(br);
          })
      .filter(Optional::isPresent)
      .map(Optional::get)
      .flatMap(...something that reads the file contents...) // From here, the Stream doesn't content something that gives access to the FileReaders
  </code></pre>
  
  <p>After doing some other mappings, etc, I finally lose the <code>FileReader</code>s in the sequel.</p>
  
  <p>I first thought the garbage collector is able to do it when needed, but I've experienced OS descriptor exhaustion when <code>filenames</code> is a long <code>Stream</code>.</p>