2012-12-29 36 views
0

我创建了一个算法来读取文件并检查用户输入的多个问题。我正在使用Netbeans,它建议尝试使用资源。我不确定的是关闭文件。当我第一次创造了我的算法,我把file.close()在错误的地方,因为它无法达到的,因为有之前“返回”声明:用试用资源环绕扫描仪

while (inputFile.hasNext()) { 
     String word = inputFile.nextLine(); 
     for (int i = 0; i < sentance.length; i++) { 
      for (int j = 0; j < punc.length; j++) { 
       if (sentance[i].equalsIgnoreCase(word + punc[j])) { 

        return "I am a newborn. Not even a year old yet."; 
       } 
      } 
     } 
    } 
    inputFile.close(); // Problem 

所以我固定它这样的:

 File file = new File("src/res/AgeQs.dat"); 
    Scanner inputFile = new Scanner(file); 
    while (inputFile.hasNext()) { 
     String word = inputFile.nextLine(); 
     for (int i = 0; i < sentance.length; i++) { 
      for (int j = 0; j < punc.length; j++) { 
       if (sentance[i].equalsIgnoreCase(word + punc[j])) { 
        inputFile.close(); // Problem fixed 
        return "I am a newborn. Not even a year old yet."; 
       } 
      } 
     } 
    } 

是,当我将它设置了错误的方式,Netbeans的建议这个问题:

 File file = new File("src/res/AgeQs.dat"); 
    try (Scanner inputFile = new Scanner(file)) { 
     while (inputFile.hasNext()) { 
      String word = inputFile.nextLine(); 
      for (int i = 0; i < sentance.length; i++) { 
       for (int j = 0; j < punc.length; j++) { 
        if (sentance[i].equalsIgnoreCase(word + punc[j])) { 

         return "I am a newborn. Not even a year old yet."; 
        } 
       } 
      } 
     } 
    } 

是Netbeans的纠正我的代码,或只是删除文件的结束?这是一个更好的方式去做这件事吗?除非我确切知道发生了什么,否则我不喜欢使用代码。

+2

让问题更广泛 - 他们会将它关闭太宽,使其具体 - 太近了。 – Stepan

回答

1

阅读this,这是Java 7的try-with-resource模块。

try-with-resources语句确保每个资源在语句结束时关闭。

Java 6不支持try-with-resources;您必须明确关闭IO流。

1

是Netbeans纠正我的代码,或者只是删除文件的关闭?

它正在纠正你的代码。 try-with-resource在implicit finally子句中关闭了资源部分中声明/创建的资源。 (所有资源必须实现Closeable接口...)

5

try-with-resources提供了保证AutoCloseable资源(如扫描程序)始终处于关闭状态的保证。闭合由javac约隐含添加。 as

Scanner inputFile = new Scanner(file); 
try { 
    while (inputFile.hasNext()) { 
     .... 
    } 
} finally { 
    inputFile.close(); 
} 

顺便说一句,在您的代码中有一个问题,Netbeans未能注意到。扫描仪的方法不会抛出IOException,但会压缩它。使用Scanner.ioException检查读取文件时是否发生异常。