0

假设我有一个引发异常的自定义阅读器对象:

public StationReader {

    public StationReader(String inFile) throws FileNotFoundException {
        Scanner scan = new Scanner(inFile);

        while (scan.hasNextLine() {
            // blah blah blah
        }

        // Finish scanning
        scan.close();       
    }
}

我在另一个类 Tester 中调用 StationReader:

public Tester {

    public static void main(String[] args) {

        try {
            StationReader sReader = new StationReader("i_hate_csv.csv");

        } catch (FileNotFoundException e) {
            System.out.println("File not found arggghhhhhh");
        } finally {
            // HOW TO CLOSE SCANNER HERE??
        }
    }
}

现在让我们想象一下,在扫描这些行时,抛出了一个异常,所以scan.close()永远不会被调用。

在这种情况下,我该如何关闭扫描仪对象?

4

1 回答 1

4

将读取过程写在try-with-resources语句中,但不要捕获任何异常,只需将它们传递回调用者,例如...

public class CustomReader {

    public CustomReader(String inFile) throws FileNotFoundException {
        try (Scanner scan = new Scanner(inFile)) {
            while (scan.hasNextLine()) {
                // blah blah blah
            }
        }
    }
}

该语句会在代码存在块try-with-resource时自动关闭资源try

仅供参考:finally曾经用于此,但是当您有多个资源时,它会变得混乱。所有的冰雹try-with-resources

于 2018-11-04T22:45:40.533 回答