简体   繁体   English

java.io.IOException:句柄无效

[英]java.io.IOException: The handle is invalid

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 java.io.IOException:句柄无效

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 . 我相信每当我调用arrayListWithNumbers()方法时我都会收到错误,当我尝试显示默认构造函数中的字节数时,它完全正常工作并显示101281 bytes的计数。

Well you're closing input in the finally block of the constructor, before you actually start using it. 那么你在构造函数的finally块中关闭input ,然后才真正开始使用它。 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. 将结束部分从构造函数移动到完成后将调用的某个位置,例如调用arrayListWithNumbers或从main调用的单独close方法。

I think you are confusing finally with finalize() which you should not use for this purpose either. 我认为你finally finalize()感到困惑,你不应该为此目的使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM