java.io.IOException:句柄无效 [英] java.io.IOException: The handle is invalid

查看:303
本文介绍了java.io.IOException:句柄无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自己学习编程,但我仍然试图掌握它.我收到以下错误:

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:句柄无效

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的计数.

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.

推荐答案

在实际开始使用它之前,您要在构造函数的finally块中关闭input.将结束部分移出构造函数,移至完成后将被调用的地方,例如在arrayListWithNumbers的调用下方或从main调用的单独的close方法.

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.

我认为您正在将finallyfinalize()混淆,您也不应该将其用于此目的.

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

这篇关于java.io.IOException:句柄无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆