我正在尝试关闭finally块中的Scanner和PrintStream,它们在try块中声明。问题是,如果try块由于异常而失败,则Scanner和Printstream永远不会被声明,从而导致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();
}
编辑:谢谢你的回答,我在没有尝试资源的情况下解决了这个问题,在尝试块之前声明Scanner和Printstream,然后在尝试块中初始化它们,如下所示:
Scanner fileScanner = null;
PrintStream output = null;
try {
fileScanner = new Scanner(readFile);
output = new PrintStream(new FileOutputStream(writeFile,false));
...
}
您可以使用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
块后,它们将自动关闭