【问题标题】:Scanner - Ignore new line at end of file扫描仪 - 忽略文件末尾的新行
【发布时间】:2014-03-06 09:59:24
【问题描述】:

在进入/忽略文件 reg.txt 中的最后一个新行时,我需要一些帮助来退出。截至目前,当它到达最后一行时,我得到一个错误,不包含任何内容。

public String load() {
        list.removeAllElements();
        try {
            Scanner scanner = new Scanner(new File("reg.txt"));

            while (scanner.hasNextLine()) {
                String lastname = scanner.next();
                String firstname = scanner.next();
                String number = scanner.next();
                list.add(new Entry(firstname, lastname, number));
            }
            msg = "The file reg.txt has been opened";
            return msg;
        } catch (NumberFormatException ne) {
            msg = ("Can't find reg.txt");
            return msg;
        } catch (IOException ie) {
            msg = ("Can't find reg.txt");
            return msg;
        }
    }

示例 reg.txt:

Allegrettho     Albert          0111-27543
Brio            Britta          0113-45771
Cresendo        Crister         0111-27440

我应该如何编辑扫描仪读取以使其忽略文件末尾的新行?

【问题讨论】:

    标签: java newline java.util.scanner


    【解决方案1】:

    在循环结束时,做

    Scanner.nextLine();
    

    【讨论】:

      【解决方案2】:

      一个干而肮脏的方法是在每个scanner.next()之前检查是否有下一行。

      if(scanner.hasNextLine())
      {
        lastname = scanner.next();
      }
      

      或在字符串姓氏之后:

      if(!lastname.isEmpty())
      {
         //continue here...
      }
      

      【讨论】:

        【解决方案3】:

        您可以为 Entry 参数添加验证,如果有任何空行,您将跳过它。

        if(firstname != null || lastname != null || number != null) {
            list.add(new Entry(firstname, lastname, number));
        }
        

        【讨论】:

        • 不幸的是,存储不是问题,而是扫描仪读取。所以,我仍然收到错误。
        【解决方案4】:

        最简单的方法可能是将您的数据集合包含在 if 语句中以检查scanner.next() 是否不为空:

        while (scanner.hasNextLine()) {
            if(!scanner.next().equals("")&&!scanner.next()==null){
                String lastname = scanner.next();
                String firstname = scanner.next();
                String number = scanner.next();
                list.add(new Entry(firstname, lastname, number));
            }
        }
        

        否则,我会查看您的 hasNextLine 方法,了解当下一行为空时说“是的,我有下一行”的逻辑;)

        【讨论】:

          【解决方案5】:

          不要使用next() 读取最后一个字段,而是使用nextLine()。这将使扫描仪超过行尾,但不会在结果中返回行尾字符。

          scanner.hasNextLine() 将变为false,因此循环不会再次开始。

          while (scanner.hasNextLine()) {
              String lastname = scanner.next();
              String firstname = scanner.next();
              String number = scanner.nextLine();
              list.add(new Entry(firstname, lastname, number));
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多