簡體   English   中英

使用 try-with-resources 或在 sonarqube 的“finally”子句中關閉此“BufferedReader”

[英]Use try-with-resources or close this "BufferedReader" in a "finally" clause in sonarqube

我正在嘗試實現此代碼,但在sonarqube中的“最終”子句中獲得了一些“使用 try-with-resources 或關閉此“BufferedReader”我已經閱讀了其他人的答案,但他們都沒有幫助我,所以任何人都可以指導我到底需要更改代碼的位置(對於 sonarqube 中的上述錯誤確實沒有任何背景)

     public static List getlockList(String componentPath) throws IOException 
     {
         List<String> listOfLines = new ArrayList<String>();
         BufferedReader bufReader = null;
         try {
              bufReader = new BufferedReader(new FileReader(componentPath));
              String line = bufReader.readLine();

              //Looking for the pattern starting with #(any number of #) then any String after that
              Pattern r = Pattern.compile("(^[#]*)(.*)");

              while (line != null) {
                  line = line.trim();
                  if(!("".equals(line))) 
                  {
                      if(line.matches("^#.*"))
                      {
                          Matcher m = r.matcher(line);
                          if (m.find( )) 
                          {
                              //System.out.println("Found value: " + m.group(2) );
                              unlockList.add(m.group(2).trim());
                          }
                    }
                    else
                    {
                        listOfLines.add(line);
                        //empty lines removed 
                    }

                    line = bufReader.readLine();
                  }
                  else
                  {
                    line = bufReader.readLine();
                  }
             }
         } catch(Exception ex) {
             log.info(ex);
         } finally {
             if (bufReader != null) 
                 bufReader.close();
         }

         return listOfLines;
    } 

BufferedReader 應在類似於以下內容的 try 塊中創建:

public static List getlockList(String componentPath) throws IOException 
 {
  List<String> listOfLines = new ArrayList<String>();
  try(BufferedReader bufReader = new BufferedReader(new FileReader( componentPath)))
  {
      // do your magic
  }

  return listOfLines;
}

即使發生異常,Reader 也會自動關閉。 還有一個規則描述,涵蓋了一個兼容的解決方案: https : //rules.sonarsource.com/java/tag/java8/RSPEC-2093

讀取文件行的​​整個邏輯必須用 try catch 塊包圍。 這是因為您可能會遇到FileNotFoundExceptionFileNotFoundException 閱讀完這些行后,您必須在final子句中關閉緩沖區讀取器,因為如果拋出異常,則BufferedReader可能不會關閉,並且您將遇到內存泄漏問題。

您還可以使用 try with resources 這是處理可關閉資源(如BufferedReader )的新方法。 那么你就不需要調用bufReader.close();

這是帶有示例的 oracle 文檔: https : //docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM