Java 当我试图在finally块中关闭BufferedReader时,为什么eclipse会抱怨?
这是我的密码:Java 当我试图在finally块中关闭BufferedReader时,为什么eclipse会抱怨?,java,eclipse,exception,bufferedreader,try-catch-finally,Java,Eclipse,Exception,Bufferedreader,Try Catch Finally,这是我的密码: public static String readFile() { BufferedReader br = null; String line; String dump=""; try { br = new BufferedReader(new FileReader("dbDumpTest.txt")); } catch (FileN
public static String readFile()
{
BufferedReader br = null;
String line;
String dump="";
try
{
br = new BufferedReader(new FileReader("dbDumpTest.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
System.exit(0);
}
try
{
while( (line = br.readLine()) != null)
{
dump += line + "\r\n";
}
}
catch (IOException e)
{
System.out.println(e.getMessage() + " Error reading file");
}
finally
{
br.close();
}
return dump;
因此eclipse正在抱怨由br.close()引起的未处理IO异常代码>
为什么这会导致IO异常
我的第二个问题是为什么eclipse不抱怨以下代码:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// releases any system resources associated with reader
br.close();
// creates error
br.read();
}catch(IOException e){
// IO error
System.out.println("The buffered reader is closed");
}finally{
// releases any system resources associated
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
如果可能的话,请你用外行的语言解释,我将不胜感激。提前感谢您的帮助这两个代码示例都应该有编译器错误,抱怨未处理的IOException。Eclipse在这两个代码示例中为我显示了这些错误
原因是close
方法在finally
块中调用时抛出一个IOException
,一个选中的异常,它位于try
块之外
修复方法是使用Java 1.7+中提供的。声明的资源是隐式关闭的
try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
// Your br processing code here
}
catch (IOException e)
{
// Your handling code here
}
// no finally necessary.
在Java1.7之前,您需要将对close()
的调用封装在finally
块中自己的try-catch块中。要确保所有内容都已关闭和清理,需要大量冗长的代码
finally
{
try{ if (is != null) is.close(); } catch (IOException ignored) {}
try{ if (isr != null) isr.close(); } catch (IOException ignored) {}
try{ if (br != null) br.close(); } catch (IOException ignored) {}
}
使用将大大简化代码。它会抱怨,好吧。我怀疑第二个代码来自的方法有一个抛出
声明。或者在该代码周围有一个try…catch
。请共享完整的方法。除非您隐藏了什么,否则第二个代码段应该存在与未处理的IOException
相同的问题。因此,在执行try块中的代码后,我在try with resources语句中声明的BufferedReader将自动关闭??是的,这就是try with resources的点。从我上面使用的链接中可以看到:“try with resources语句确保每个资源在语句末尾关闭。”