在封闭类之外调用扫描器对象时,该如何关闭呢?

时间:2018-11-04 22:42:09

标签: java exception-handling java.util.scanner

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

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

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

1 个答案:

答案 0 :(得分:4)

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