扫描仪 - 忽略文件末尾的新行

时间:2014-03-06 09:59:25

标签: java newline java.util.scanner

在进入/忽略文件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

我应该如何编辑扫描仪读数,以便它忽略文件末尾的新行?

5 个答案:

答案 0 :(得分:1)

在循环结束时,执行

Scanner.nextLine();

答案 1 :(得分:0)

如果有下一行,那么在每个scanner .next()之前检查一个干燥和脏的方法。

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

或在String lastname之后:

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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方法,当下一行为空时,说'是的我有下一行'的逻辑;)

答案 4 :(得分:0)

而不是使用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));
}
相关问题