猿问

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

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


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()永远不会被调用。


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


郎朗坤
浏览 138回答 1
1回答

HUX布斯

在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🎉
随时随地看视频慕课网APP

相关分类

Java
我要回答