【问题标题】:How to read a file line by line with a scanner and use the info?如何使用扫描仪逐行读取文件并使用信息?
【发布时间】:2023-03-17 04:15:01
【问题描述】:

我对 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()));

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

【问题讨论】:

  • 为什么要马上关闭Scanner,这样就关闭了System.in
  • 因为我只从键盘读过一次,不应该是这样吗?

标签: java java.util.scanner filereader


【解决方案1】:

您正在关闭teclat.close() 处的Scanner,然后您尝试读取它的几行。

【讨论】:

  • 如果我删除它,当我输入文件名时没有任何反应。
  • 替换为 teclat.nextLine();然后您的输入将被处理。
【解决方案2】:

你做到了

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

后来

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

由于您已经关闭了名为“文件”的扫描仪,因此您无法从扫描仪重新读取它。 如果您需要为第一个 teclat.nextLine() 获取的输入值,请将其保存在某处以备后用。所以就像

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

//blabla

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

【讨论】:

    【解决方案3】:

    正如@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();
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 2012-11-02
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多