2012-04-14 148 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()你不應該爲此目的使用。