如何在封闭 class 之外调用扫描仪对象时关闭它?

How to close scanner object when it is called outside of the enclosing class?

假设我有一个抛出异常的自定义 reader 对象:

public StationReader {

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

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

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

我在另一个 class 中调用 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() 永远不会被调用。

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

把读取的过程写在一个try-with-resources statement中,但是不捕获任何异常,只是让它们传回给调用者,例如...

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

时自动关闭资源

fyi: finally 以前是用来做这个的,但是当你有多个资源时,它就变得很乱了。冰雹 try-with-resources