![](/img/trans.png)
[英]Use try-with-resources or close this "BufferedReader" in a "finally" clause in sonarqube
[英]Why is eclipse complaining when I try to close BufferedReader in finally block?
這是我的代碼:
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異常br.close();
為什么這會導致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();
}
}
}
如果可以的話,請以Laymen的名義保留解釋,我們將不勝感激。 我在這里先向您的幫助表示感謝
這兩個代碼示例都應具有抱怨未處理的IOException的編譯器錯誤。 Eclipse在我的兩個代碼示例中將它們顯示為錯誤。
原因是close
方法在try
塊之外的finally
塊中調用時, close
方法將拋出IOException
,這是一個經過檢查的異常。
解決方法是使用try-with-resources語句 ,該語句在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.
在Java 1.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) {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.