Sonarqube问题-将此“ try”更改为try-with-resources如何处理条件资源?

问题描述

检查了有关此主题的类似问题,但未找到用例的解决方案。
以下方法Major code smell的声纳问题显示为-Change this "try" to a try-with-resources.

private void readExcel() {
        Workbook workbook = null;
        BufferedReader br = null;
        
        try {
            File file = path.toFile();
            if (file.getName().endsWith(FILE_TYPES.XLS.value) && (file.length() / (1024 * 1024)) < 25) {
                workbook = new hssfWorkbook(new POIFSFileSystem(file));
                Sheet sheet = workbook.getSheetAt(0);
                readExcel(sheet);
            } else if ((file.getName().endsWith(FILE_TYPES.XLSX.value)) && (file.length() / (1024 * 1024)) < 25) {
                workbook = new XSSFWorkbook(file);
                Sheet sheet = workbook.getSheetAt(0);
                readExcel(sheet);
            } else if (file.getName().endsWith(FILE_TYPES.CSV.value)) {
                // Apache POI cant read/write CSV. Hence using Java IO.
                br = new BufferedReader(new FileReader(file));
                readExcel(br);
            }
        } catch (IOException | InvalidFormatException ex) {
                // set invalid flags and call clean-up
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                // set invalid flags and call clean-up
            }
        } // try-catch-finally closed
    }

这是假阳性声纳问题吗?

解决方法

HSSFWorkbookAutoCloseable
XSSFWorkbookAutoCloseable
BufferedReaderAutoCloseable

他们都需要自己的资源尝试

摆脱Workbook workbook = null;BufferedReader br = null;以及finally块中的代码,因为这都是旧式的带资源预试。

private void readExcel() {
    try {
        File file = path.toFile();
        if (file.getName().endsWith(FILE_TYPES.XLS.value) && (file.length() / (1024 * 1024)) < 25) {
            try (Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(file))) {
                Sheet sheet = workbook.getSheetAt(0);
                readExcel(sheet);
            }
        } else if ((file.getName().endsWith(FILE_TYPES.XLSX.value)) && (file.length() / (1024 * 1024)) < 25) {
            try (Workbook workbook = new XSSFWorkbook(file)) {
                Sheet sheet = workbook.getSheetAt(0);
                readExcel(sheet);
            }
        } else if (file.getName().endsWith(FILE_TYPES.CSV.value)) {
            // Apache POI cant read/write CSV. Hence using Java IO.
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                readExcel(br);
            }
        }
    } catch (IOException | InvalidFormatException ex) {
        // set invalid flags and call clean-up
    }
}