java.io.IOException: The handle is invalid

2020-05-08 17:36发布

I am trying to learn programming on my own time and I am still trying to get the hang of it. I am getting the following error:

java.io.IOException: The handle is invalid

Here is my code

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();
}
}

I believe I'm getting the error whenever I invoke the arrayListWithNumbers() method, when I attempt to show the number of bytes in the default constructor, then it works perfectly fine and shows a tally of 101281 bytes.

标签: java file-io
1条回答
SAY GOODBYE
2楼-- · 2020-05-08 18:07

Well you're closing input in the finally block of the constructor, before you actually start using it. Move the closing part out of the constructor to somewhere it will be called when you're done, such as below the call to arrayListWithNumbers or a separate close method that you call from you main.

I think you are confusing finally with finalize() which you should not use for this purpose either.

查看更多
登录 后发表回答