我目前正在为我的一个 java 类编写一个程序,并且我一直在读取文件时遇到墙壁!我正在使用 JTable 来显示信息,因此当从文件中读取信息时,它会被添加到一行中。只要有空白行,扫描仪就无法读取它并抛出错误!我在最后一个扫描线上得到一个 java.util.NoSuchElementException !截至目前,我正在起诉两个单独的扫描仪。我曾尝试使用 String.split 方法,这也给了我一个错误(ArrayIndexOutOfBoundsException:0)。我将在下面发布阅读保存方法(两个扫描仪版本和拆分)。
私人无效读取(){
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(); 扫描仪=空;
} 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);
}
}