使用try-with-resources或在“ finally”子句中关闭此“ BufferedReader”

时间:2019-05-15 13:55:51

标签: java try-catch bufferedreader

一直在寻找解决此问题的方法。阅读所有先前的答案,但没有一个帮助我。 SonarQube可能有任何错误吗?

public class Br {

    public String loader(String FilePath){

        BufferedReader br;
        String str = null;
        StringBuilder strb = new StringBuilder();
        try {
            br = new BufferedReader(new FileReader(FilePath));
            while ((str = br.readLine()) != null) {
                strb.append(str).append("\n");
            }
        } catch (FileNotFoundException f){
            System.out.println(FilePath+" does not exist");
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strb.toString();
    }
}

3 个答案:

答案 0 :(得分:5)

您未致电(None,None,9),这意味着存在资源泄漏的风险。为了可靠地关闭br.close(),您有两个选择:

使用BufferedReader块:

finally

使用带有资源的public String loader(String FilePath) { // initialize the reader with null BufferedReader br = null; String str = null; StringBuilder strb = new StringBuilder(); try { // really initialize it inside the try block br = new BufferedReader(new FileReader(FilePath)); while ((str = br.readLine()) != null) { strb.append(str).append("\n"); } } catch (FileNotFoundException f) { System.out.println(FilePath + " does not exist"); return null; } catch (IOException e) { e.printStackTrace(); } finally { // this block will be executed in every case, success or caught exception if (br != null) { // again, a resource is involved, so try-catch another time try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return strb.toString(); } 语句:

try

答案 1 :(得分:2)

似乎您只想从文件中读取所有行。您可以使用:

public String loader(String FilePath) {
    try(Scanner s = new Scanner(new File(FilePath).useDelimiter("\\A")) {
        return s.hasNext() ? s.next() : null;
    } catch(IOException e) {
        throw new UncheckedIOException(e);
    }
}

答案 2 :(得分:0)

您编写的代码确实在泄漏资源,因为您没有关闭BufferedReader。以下代码片段可以解决问题:

public String loader(String filePath){
    String str = null;
    StringBuilder strb = new StringBuilder();
    // try-with-resources construct here which will automatically handle the close for you
    try (FileReader fileReader = new FileReader(filePath); 
         BufferedReader br = new BufferedReader(fileReader);){
        while ((str = br.readLine()) != null) {
            strb.append(str).append("\n");
        }
    }
    catch (FileNotFoundException f){
        System.out.println(filePath+" does not exist");
        return null;
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return strb.toString();
}

如果此代码仍然有问题,那么是的,这是SonarQubes的错误:-)