2013-02-16 58 views
0

我正在个人项目上工作,但我有一个问题,我似乎无法弄清楚。扫描仪故障。没有脚本错误,但控制台给出错误

public void setvars() { 
    File file = new File("config.txt"); 

    try { 
     Scanner sc = new Scanner(file); 

     while(sc.hasNextLine()) { 
      //int OESID = sc.nextInt(); this variable isnt used yet. 
      String refresh = sc.next(); 
      sc.close(); 

      textFieldtest.setText(refresh); 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

在它告诉我的错误是while(sc.hasNextLine()) {控制台我不能弄明白。任何指针/建议将不胜感激!

+0

有什么错误?什么是扫描仪对象? – 2013-02-16 15:55:48

回答

0

问题是您在使用扫描仪时正在关闭扫描仪。

修改代码以关闭扫描仪一旦你用它做:

while(sc.hasNextLine()) { 
     //int OESID = sc.nextInt(); this variable isnt used yet. 
     String refresh = sc.next(); 

     textFieldtest.setText(refresh); 
    } 
    sc.close(); 

这也许应该是,每当你处理任何资源使用通用的模式 - 确保您关闭它只有一次,你”确信你不再需要它了。

你可以让你的生活更容易,如果你使用的是Java 7通过使用新的尝试,与资源的功能,它会自动关闭资源:

try(Scanner sc = new Scanner("/Users/sean/IdeaProjects/TestHarness/src/TestHarness.java")) { 
     while(sc.hasNextLine()) { 
      // do your processing here 
     } 
    } // resource will be closed when this block is finished 
+0

啊!完善!非常感谢! – user2078674 2013-02-16 17:08:19