2012-04-14 145 views
0

我试图在自己的时间学习编程,而我仍然试图去掌握它。我收到以下错误:java.io.IOException:句柄无效

java.io.IOException: The handle is invalid

这里是我的代码

public class PrimeFinder { 
private int[] prime; 
FileInputStream input = null; 
//default contructor uses the premade file prime.txt that has the first 10000 digits of pi 
public PrimeFinder() throws IOException { 
    try{ 
     input = new FileInputStream ("primes.txt"); 
    } 
    finally { 
     if (input != null) { 
      input.close(); 
     } 
    } 
} 
//constructor with a predefined text file to use. 
public PrimeFinder(String txtFile) throws IOException { 
    try{ 
     input = new FileInputStream(txtFile); 
    } 
    finally { 
     if (input != null) { 
      input.close(); 
     } 
    } 
} 
public static void main(String[] args) throws IOException{ 

    PrimeFinder tester = new PrimeFinder(); 
    tester.arrayListWithNumbers(); 
} 
} 

我相信,我发现了错误,每当我调用arrayListWithNumbers()方法,当我试图表现出的字节数默认的构造函数,然后它工作得很好,并显示了一个理货101281 bytes

+2

您不必猜测出现错误的位置,堆栈会追踪到您发生错误的地方 - 在调用链中跟踪它,直到看到对代码的引用。 – 2012-04-14 00:44:26

回答

2

那么在你真正开始使用它之前,你正在构造函数的finally块中关闭input。将结束部分从构造函数中移出,直到完成后调用该函数,例如调用arrayListWithNumbers或您从main调用的单独close方法。

我认为你很困惑finallyfinalize()你不应该为此目的使用。