我一直在尝试从外部 .txt 文件读入“任务”列表以形成待办事项列表,但尝试将多行读入列表会出现以下错误,这告诉我:数组未正确扩展以适应额外的行。
java.lang.ArrayIndexOutOfBoundsException: 1
但是我请求帮助的是让数组正确填充,据我所知,它应该来自此函数调用。
public void loadList(boolean showStatus) {
myList.clear();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while (line != null) {
String[] tokens = line.split(",");
Task item = new Task();
item.setDescription(tokens[0]);
item.setPriority(Integer.parseInt(tokens[1]));
item.setDueDate(tokens[2]);
item.setStatus(Boolean.parseBoolean(tokens[3]));
myList.add(item);
line = br.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (br != null)
try {
br.close();
} catch (IOException ex) {
Logger.getLogger(ToDoList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
(作为引用,以下是 .txt 文件的格式)
Assassinate Santa,4,12-25-19,false
Shave Bear,3,03-09-19,false
Level Canada,4,09-09-19,true
此外,显然 parseBoolean 尝试实际上并未读取 .txt 文件任务是否为真/假,并且将所有内容默认为假。
最佳答案
String[] tokens = line.split(",");
if(token.length != 4)
{
// Then you may skip this line and proceed to next line
continue;
}
// Or do the reading tokens array
您可以这样做来解决评论中提到的问题。
关于java - 从文本文件加载到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095431/