title: Java -- Closing Scanner and Resource Leak
body: <p>I'm learning Java and working on some projects for fun. One issue that I have run in to is that when I use a <code>Scanner</code> object Eclipse warns me that:</p>
  
  <blockquote>
    <p>Resource Leak: 'scan' is never closed.</p>
  </blockquote>
  
  <p>So, I added a <code>scan.close();</code> at the end of my code and that takes care of the warning. </p>
  
  <p>The problem comes in because I have other classes in the same package that also use scanner objects and and Eclipse tells me to close scanner in those classes respectively. However, when I do that it seems like it closes ALL of the scanner objects and I get errors during run time. </p>
  
  <p>Here is an example of what causes the error:</p>
  
  <pre><code>import java.util.Scanner;
  public class test2 {
      public static void main(String [] args) {
          Scanner scan = new Scanner(System.in);
          int test = 0;
          do {    
              //Do stuff
              test = scan.nextInt();
              System.out.println(test);
  
              scanTest scanTest = new scanTest();
              scanTest.test();
          } while (test != 0);
  
          scan.close();       
      }
  }
  
  import java.util.Scanner;
  public class scanTest { 
      public void test() {
          Scanner scanner = new Scanner(System.in);
          int blah = scanner.nextInt();
          System.out.println(blah);
          scanner.close();
      }
  }
  </code></pre>
  
  <p>After scanner is closed in the <code>scanTest</code> class and the do loop in <code>test2</code> is entered again an error occurs at the line <code>test = scan.nextInt();</code></p>
  
  <p>I tried moving the creation of the scanner object into the do loop just to make a new object every time as well but the error still occurs. </p>
  
  <p>Not sure why this is happening or how I can make sure all my I/O objects are closed out without running into problems. </p>
  
  <p>One post I came across mentioned that when <code>System.in</code> is closed I cannot be re-opened. If this is the case would I just need to make sure a scanner object with System.in is closed at the very end of the program and @suppress all of the other scanner warnings in other classes? Or would that still leave all those scanner objects open (bad)?</p>