Uso try-con-recursos o cerca de este "BufferedReader" en una cláusula "por fin"

lol:

Estado buscando una manera de solucionar este problema. Lee todas las respuestas anteriores pero ninguno me ayudó. Podría ser cualquier error con 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();
    }
}
deHaar:

No está llamando br.close()lo que significa correr el riesgo de una pérdida de recursos. Con el fin de cerrar de forma fiable el BufferedReader, tiene dos opciones:

el uso de un finallybloque:

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();
}

usando una trydeclaración -con-recursos:

public String loader(String FilePath) {

    String str = null;
    StringBuilder strb = new StringBuilder();
    // the following line means the try block takes care of closing the resource
    try (BufferedReader 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();
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=313679&siteId=1
Recomendado
Clasificación