关闭try块中声明的finally块中的scanner/printstream

b5lpy0ml  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(329)

我正在尝试关闭finally块中的scanner和printstream,它们在try块中声明。问题是,如果try块由于异常而失败,那么scanner和printstream永远不会被声明,导致finally块出错,我想在finally块中关闭它们。代码如下:

try {
            File readFile = new File(readFileName);
            File writeFile = new File(writeFileName);
            Scanner fileScanner = new Scanner(readFile);
            PrintStream output = new PrintStream(new FileOutputStream(writeFile,false)); // overwrite
            while(fileScanner.hasNextLine()) {
                output.println(fileScanner.nextLine());
                if (!fileScanner.hasNextLine()) {
                    break;
                }
                output.println();
            }
        }

        catch (FileNotFoundException fnfe) {
            System.out.println(fnfe.getMessage());
            System.exit(0);
        }

        finally {
            fileScanner.close();
            output.close();
        }

编辑:谢谢你的回答,我不用try with resources就解决了这个问题,在try块之前声明scanner和printstream,然后在try块中初始化它们,如下所示:

Scanner fileScanner = null;
PrintStream output = null;
        try {
            fileScanner = new Scanner(readFile);
            output = new PrintStream(new FileOutputStream(writeFile,false));
            ...
        }
z9ju0rcb

z9ju0rcb1#

您可以使用try with resources构造:

File readFile = new File(readFileName);
File writeFile = new File(writeFileName);

try (Scanner fileScanner = new Scanner(readFile); PrintStream output = new PrintStream(new FileOutputStream(writeFile,false))) {

    while(fileScanner.hasNextLine()) {
        output.println(fileScanner.nextLine());
        if (!fileScanner.hasNextLine()) {
            break;
        }
        output.println();
    }

} catch (FileNotFoundException fnfe) {
    System.out.println(fnfe.getMessage());
    System.exit(0);
}

因为两者 Scanner 以及 PrintStream 实施 Autocloseable 接口,它们将在异常时或在执行 try

相关问题