打开和关闭像这样的流有什么问题?

BUR*_*RNS 5 java try-catch

所以我写了一些代码,Netbeans建议在我实例化sc的同一行上转换为try-with-resources.这个建议会在我将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");
         }
    }
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 1

问题是,sc如果您从try块返回或发生异常,您可能无法 close 。

如果您使用的是 Java 7 或更高版本,则 try-with-resources 版本是最好的:

public static void main(String[] args)  {
    try (Scanner sc = new Scanner(new File(args[0]))) {
        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }
    } catch(FileNotFoundException e){
        System.out.println("Het bestand kon niet gevonden worden.");
    } catch(Exception e){
        System.out.println("Onbekende Fout");
    }
}
Run Code Online (Sandbox Code Playgroud)

扫描仪将自动关闭。

如果您必须使用 Java 6 或更早版本,请尝试/最后:

public static void main(String[] args)  {
    Scanner sc = null;
    try {
        sc = new Scanner(new File(args[0]));
        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }
    } catch(FileNotFoundException e){
        System.out.println("Het bestand kon niet gevonden worden.");
    } catch(Exception e){
        System.out.println("Onbekende Fout");
    }
    finally {
        if (sc != null) {
            try {
                sc.close();
            }
            catch (Exception) {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在 try/finally 版本中,我们在块sc外部声明try并将其设置为null,然后在finally(无论 中发生什么情况都会运行try)中,如果不允许null 该操作抛出异常,我们将关闭它(因为我们可能已经在抛出异常的过程中,并且不想中断它)。