title: What is the diff between declaring a Stream with try-with-resources statement or not?
body: <p>In Java 8, Stream (which is AutoCloseable) cannot be reused, once it is consumed or used, the stream will be closed. So what is the utility to declared with try-with-resources statement ?</p>
  
  <p>Example with try-with-resources statement :</p>
  
  <pre><code>    public static void main(String[] args) throws IOException {
  
      try (Stream&lt;Path&gt; entries
              = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS)) {
          entries.forEach(x -&gt; System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point
          //..
          System.out.println("Still in the Try Block");
      } //The entries will be closed again because it is declared in the try-with-resources statement
  }
  </code></pre>
  
  <p>And here the same example without the try catch block</p>
  
  <pre><code>public static void main(String[] args) throws IOException {
          Stream&lt;Path&gt; entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS);
          entries.forEach(x -&gt; System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point
          System.out.println("Is there a risk of resources leak ?");
      }
  </code></pre>
  
  <p>Which one is safer ? </p>
  
  <p>After some answers I update my code to check if the stream has been closed or not: </p>
  
  <p>Here the new code : </p>
  
  <pre><code>public static void main(String[] args) throws IOException {
  
      resourceWithTry();
      resourceWithoutTry();
  }
  
  private static void resourceWithTry() throws IOException {
      try (Stream&lt;Path&gt; entries
              = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -&gt; System.out.println("The Stream is closed"))) {
          entries.forEach(x -&gt; System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point
          System.out.println("Still in the Try Block");
      } //The entries will be closed again because it is declared in the try-with-resources statement
  }
  
  private static void resourceWithoutTry() throws IOException {
      Stream&lt;Path&gt; entries
              = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -&gt; System.out.println("Without Try: The Stream is closed"));
      entries.forEach(x -&gt; System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point
      System.out.println("Still in the Try Block");
  }
  </code></pre>