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()) {我无法弄清楚。任何指针/建议将不胜感激!

4

1 回答 1

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-with-resource 功能让您的生活更加轻松,该功能将自动关闭资源:

    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
于 2013-02-16T16:08:19.233 回答