从空行读取文件

时间:2012-04-13 16:38:36

标签: java java.util.scanner

我目前正在为我的一个java类开发一个程序,并且我一直在运行一个带文件读取的墙!我正在使用JTable来显示信息,因此当从文件中读取信息时,它会被添加到一行中。只要有一个空行,扫描仪就无法读取它并抛出错误!我在最后一条扫描线上得到一个java.util.NoSuchElementException!从右到右不,我起诉两个独立的扫描仪。我曾尝试使用String.split方法,这也给了我一个错误(ArrayIndexOutOfBoundsException:0)。我将在下面发布一个保存方法(两个扫描仪版本和拆分)。

private void read(){

    try {
        Scanner scanner = new Scanner(new File("games.dat"));


        scanner.useDelimiter(System.getProperty("line.separator"));


        while (scanner.hasNext()) {
      String[] tableRow = new String[6];
            Scanner recIn = new Scanner(record);
            recIn.useDelimiter("\\s*\\|\\s*");
            tableRow[0] = recIn.next();
            tableRow[1] = recIn.next();
            tableRow[2] = recIn.next();
            tableRow[3] = recIn.next();
            tableRow[4] = recIn.next();
            //recIn.next();
            recIn.close();
            model.addRow(new Object[]{tableRow[0],
     tableRow[1], tableRow[2],
     tableRow[3], tableRow[4]});

} scanner.close();              scanner = null;

    } catch (Exception ex) {
        JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in        zipped file!",
                "Warning!", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();

    }
}



private void save() {

    for (int i = 0; i < model.getRowCount(); i++) {


        String data = model.getValueAt(i, 0) + "|" + model.getValueAt(i, 1)
                + "|" + model.getValueAt(i, 2) + "|" + model.getValueAt(i, 3)
                + "|" + model.getValueAt(i, 4) + "|";
        games.add(data);

}

 try {
        for (int i = 0; i < games.size(); i++) {
            fileOut.println(games.get(i));
        }
        fileOut.close();

    } catch (Exception ex) {
        JOptionPane.showConfirmDialog(null, "Could not connect to file! Make sure you are not in zipped file!",
                "Warning!", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE);

    }
}

2 个答案:

答案 0 :(得分:2)

如果该行为空,则

recIn.next();将失败,并使用hasNext()保护它:

Scanner recIn = new Scanner(record); 
recIn.useDelimiter("\\s*\\|\\s*");
if (recIn.hasNext()) {
  tableRow[0] = recIn.next(); 
  tableRow[1] = recIn.next(); 
  tableRow[2] = recIn.next(); 
  tableRow[3] = recIn.next(); 
  tableRow[4] = recIn.next();
}

这假定当记录中有一个元素时,它们都在那里。如果无法保证这一点,则需要使用next()保护每个hasNext()来电并确定在记录中间用完元素时要执行的操作。

此外,您似乎有一个无限循环:

while (scanner.hasNext()) {
  // no calls to scanner.next()
}

你是否从该循环的顶部遗漏了String record = scanner.next();

答案 1 :(得分:1)

从java.util.Scanner JavaDoc中,有这个方法,skip():

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#skip%28java.util.regex.Pattern%29

最后一行写道:“请注意,通过使用可以匹配任何内容的模式,例如sc.skip(”[\ t] *“),可以跳过没有冒险NoSuchElementException的事情。”

所以,也许可以添加为循环的第一个调用,scanner.skip(“[\ t] *);