我正在尝试关闭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));
...
}
1条答案
按热度按时间z9ju0rcb1#
您可以使用try with resources构造:
因为两者
Scanner
以及PrintStream
实施Autocloseable
接口,它们将在异常时或在执行try
块