Java 从具有空行的文件中读取

Java 从具有空行的文件中读取,java,java.util.scanner,Java,Java.util.scanner,我目前正在为我的一个java类编写一个程序,我一直在读文件!我使用JTable来显示信息,因此当从文件中读取信息时,它会添加到一行中。当有空行时,扫描仪无法读取并抛出错误!我在最后一行扫描中得到一个java.util.NoSuchElementException!不,我正在起诉两个不同的扫描仪。我试图使用String.split方法,但该方法也给了我一个错误(ArrayIndexOutOfBoundsException:0)。我将在下面发布一个保存方法(两个扫描仪版本和拆分) 私有void re

我目前正在为我的一个java类编写一个程序,我一直在读文件!我使用JTable来显示信息,因此当从文件中读取信息时,它会添加到一行中。当有空行时,扫描仪无法读取并抛出错误!我在最后一行扫描中得到一个java.util.NoSuchElementException!不,我正在起诉两个不同的扫描仪。我试图使用String.split方法,但该方法也给了我一个错误(ArrayIndexOutOfBoundsException:0)。我将在下面发布一个保存方法(两个扫描仪版本和拆分)

私有void read(){

}scanner.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);
        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);
}捕获(异常示例){
JOptionPane.showConfirmDialog(null,“无法连接到文件!请确保您不在压缩文件中!”,
“警告!”,JOptionPane.OK\u选项,
JOptionPane.ERROR\u消息);
例如printStackTrace();
}
}
私有void save(){
对于(int i=0;i
}

试试看{
对于(int i=0;i
recIn.next()将失败,请使用
hasNext()

这假设当记录上有一个元素时,所有元素都在那里。如果不能保证这一点,则需要保护每个<代码> NEXT()>代码>用<代码> HasNeXT()/Cuffe调用,并决定当在记录中间用完元素时该怎么做。 此外,您似乎有一个无限循环:

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

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

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

最后一行写着,“注意,通过使用不匹配任何内容的模式,可以跳过某些内容而不冒NoTouchElementException的风险,例如sc.skip([\t]*”)


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

是的,很抱歉,我忘了在我的原始帖子中包含这行代码。我已经按照你的建议做了,现在它工作了!但是现在,当分隔字段中没有任何内容时,它会将null打印到tableput
model.addRow(新对象[]{tableRow[0],tableRow[1],tableRow[2],tableRow[3],tableRow[4]});
位于防护装置的主体内
if
,因此只有在能够解析值的情况下才能向表中添加值(注意:调用
recIn.close()
应该在
if
之外:无论是否可以读取,都不希望将其关闭)另外,如果这解决了您的问题,请接受我的回答。当程序退出时,我仍然会收到空值。每次保存输出文件时,都会向其添加一个空值。这就是文件在运行、保存和关闭三次后的样子:| | null | null | null | null | null | | null | | | | | | | | | | | | | | | null | null |每一次其中:| | | null | null |位于新行
 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);

    }
}
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();
}
while (scanner.hasNext()) {
  // no calls to scanner.next()
}