所以我写了一些代码,并且Netbeans建议转换为在我实例化sc的同一行上尝试使用资源。这个建议在我把while循环后面的sc.close()的时候弹出来。我不太明白为什么这种密切的操作很糟糕。打开和关闭像这样的流是什么错误?
public static void main(String[] args) {
try{
Scanner sc = new Scanner(new File(args[0]));
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
sc.close();
} catch(FileNotFoundException e){
System.out.println("Het bestand kon niet gevonden worden.");
} catch(Exception e){
System.out.println("Onbekende Fout");
}
}
有一种叫做'finally'的东西。 – devnull
它不在while循环中关闭操作... – BURNS