package Date20200617; import java.io.Console; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.Scanner; public class PlayCartoons { public static void main(String[] args) { System.out.println(FileUtil.readFile("C:\Users\jinqi\Desktop\618.txt")); } } class FileUtil { public static String readFile(String name) { StringBuilder text = new StringBuilder(); Scanner console = null;//开启输入流
//try(Scanner console = new Scanner(new FileInputStream(name));) 这种写法自动关闭资源,就不用finally了
try { console = new Scanner(new FileInputStream(name)); while (console.hasNext()) { text.append(console.nextLine()).append(' '); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (console != null) { console.close();//在finally里写关闭输入流,但是在finally里还必须检查是不是null不然也会报错 } } return text.toString(); } }
由于finally一定会执行,scanner原来是null的,若FileInputStream创建失败,则scanner还可能是null,因此在finally里必须先检查是不是scanner是不是又参考对象,
有的话才进一步调用close()方法,否则参考至null又打算调用close()方法,反而会抛出NullPointerException。
如果return在finall之前,也会先执行finally里的,再执行返回的。