如何使用扫描仪逐行读取文件并使用信息?

时间:2014-02-25 18:15:12

标签: java java.util.scanner filereader

我对java很陌生,我有事要做,这给我带来了一些麻烦。 我必须从行读取一个文件行,然后从每行创建两个字符串并将它们用于某些东西。当我必须从文件中读取行时,一切都工作得很好。现在我有以下代码:

public static Estructura Read() throws IOException {
        Estructura list = new Estructura();

        Scanner teclat = new Scanner(System.in);
        System.out.println("Nom del fitxer: ");
        Scanner file = new Scanner(new File(teclat.nextLine()));
        teclat.close();
        String s = file.toString();

        while (file.hasNextLine() || s.charAt(14) != '(') {


                                 ...


        file = new Scanner(new File(teclat.nextLine()));
        s = file.toString();
    }

问题是,当我运行它并输入2.txt时,它会给我带来这样的错误:(文件格式正确)

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.findWithinHorizon(Unknown Source)
    at java.util.Scanner.nextLine(Unknown Source)
    at Llenguatges.Llegir(Llenguatges.java:66)
    at Llenguatges.main(Llenguatges.java:10)

第66行就是这个:

file = new Scanner(new File(teclat.nextLine()));

那么,我怎样才能阅读一行,使用它并继续阅读它,直到第二个条件发生? 我希望我能很好地解释它,提前谢谢

3 个答案:

答案 0 :(得分:1)

您正在Scanner关闭teclat.close(),然后在几行之后尝试从中读取。

答案 1 :(得分:0)

你做了

Scanner file = new Scanner(new File(teclat.nextLine()));
teclat.close();

然后再

file = new Scanner(new File(teclat.nextLine()));
s = file.toString();

由于您已经关闭名为“file”的扫描程序,因此无法从扫描程序重新读取它。 如果您需要输入第一个teclat.nextLine()的值,请将其保存到某个地方供以后使用。所以它就像

File f = new File(teclat.nextLine());
Scanner file = new Scanner(f);
teclat.close();

//blabla

s = file.toString() // or file.getName();

答案 2 :(得分:0)

正如@Henrik的回答所述,您正在第66行关闭teclat Scanner。您只需处理一个文件,并且应删除第66和67行,或者您想通过再次输入文件名来处理其他文件,因此您需要将大部分代码放在另一个while内。

public static Estructura Read() throws IOException {
    Estructura list = new Estructura();

    Scanner teclat = new Scanner(System.in);
    while (__SomeConditionYouNeedToChooseYourself__) {
        System.out.println("Nom del fitxer: ");
        Scanner file = new Scanner(new File(teclat.nextLine()));
        String s = file.toString();

        while (file.hasNextLine() || s.charAt(14) != '(') {


                             ...

        file.close();
        }

    }
    teclat.close();
}

我忽略了一些事情,由你决定,例如你想要一个特殊的输入字符串(或只是'返回' - 这种情况不处理,BTW)决定停止,而不是创建新的文件...

相关问题