如何在try块中声明最终变量以在catch / finally块中使用?

时间:2018-06-18 12:01:34

标签: java try-catch

public StringBuffer readFile(final File inputFile) {
    String tempLine; // variable declaration
    Logger log = Logger.getLogger("Error Message");
    try {
        final FileReader fileReader = new FileReader(inputFile);
        final BufferedReader bufferedReader = new BufferedReader(fileReader);
        final StringBuffer content = new StringBuffer();
        while((tempLine=bufferedReader.readLine())!=null) {
            content.append(tempLine);
            content.append(System.getProperty("line.separator"));
        }
    }
    catch(FileNotFoundException e) {
        log.log(Level.WARNING, "File not found", e);
    }
    catch (IOException e) {
        log.log(Level.WARNING, "Couldn't Read file", e);
    }
    finally {
        bufferedReader.close();
        fileReader.close();
    }
    return content;
}

在try块中声明为final的变量fileReader和bufferedReader不能在finally块中使用。我无法在try block之外声明它们,因为它们可能会抛出异常。我希望变量也是最终的。

2 个答案:

答案 0 :(得分:1)

如果您至少使用Java 7,则可以使用try-with-resources Statement来关闭资源。这是代码:

public StringBuffer readFile(final File inputFile) {
    String tempLine; // variable declaration
    Logger log = Logger.getLogger("Error Message");
    try (final FileReader fileReader = new FileReader(inputFile)) {
        try (final BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            final StringBuffer content = new StringBuffer();
            while((tempLine=bufferedReader.readLine())!=null) {
                content.append(tempLine);
                content.append(System.getProperty("line.separator"));
            }

            return content;
        }
    } catch (FileNotFoundException e) {
        log.log(Level.WARNING, "File not found", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "Couldn't Read file", e);
    }
    // return null or throw exception;
}

答案 1 :(得分:0)

从Java 7开始,您可以编写类似的内容:

public StringBuffer readFile(final File inputFile) {
    String tempLine; // variable declaration
    Logger log = Logger.getLogger("Error Message");
    final StringBuffer content = new StringBuffer();
    try (final FileReader fileReader = new FileReader(inputFile);
            final BufferedReader bufferedReader = new BufferedReader(fileReader)){        
        while((tempLine=bufferedReader.readLine())!=null) {
            content.append(tempLine);
            content.append(System.getProperty("line.separator"));
        }
    }
    catch(FileNotFoundException e) {
        log.log(Level.WARNING, "File not found", e);
    }
    catch (IOException e) {
        log.log(Level.WARNING, "Couldn't Read file", e);
    }
    return content;
}

此处fileReaderbufferedReader已隐式关闭。