重新copy一遍代码
package exception;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileUtil3 {
public static String readFile(String name) throws FileNotFoundException {
StringBuilder text = new StringBuilder();
Scanner console = new Scanner(new FileInputStream(name));
Throwable localThrowable2 = null;
try {
while (console.hasNext()) {
text.append(console.nextLine()).append('\n');
}
} catch (Throwable localThrowable1) { // 尝试捕捉所有错误
localThrowable2 = localThrowable1;
throw localThrowable1;
} finally {
if (console != null) { // 如果console参考至Scanner实例
if (localThrowable2 != null) { // 若前面有catch到其他异常
try {
console.close(); // 尝试关闭Scanner实例
} catch (Throwable x2) { // 万一关闭时发生错误
localThrowable2.addSuppressed(x2); // 在原异常对象中记录
}
} else {
console.close(); // 若前面没有发生任何异常,就直接关闭Scanner
}
}
}
return text.toString();
}
}
|