public void importData() { List<String> files = Arrays.asList("courses.txt", "scores.txt", "credits.txt", "semesters.txt", "types.txt"); List<List<String>> fileContents = new ArrayList<>(); for (String file : files) { try (Stream<String> stream = Files.lines(Paths.get("F:\\ProgramData\\IdeaProjects\\BUPT-EBU6304G49-main\\SE0514\\src\\data\\" + file), StandardCharsets.UTF_8)) { fileContents.add(stream.collect(Collectors.toList())); } catch (IOException e) { JOptionPane.showMessageDialog(null, "An error occurred importing data"); return; } } this.courses.clear(); for (int i = 0; i < fileContents.get(0).size(); i++) { String course = fileContents.get(0).get(i); String score = fileContents.get(1).get(i); String credit = fileContents.get(2).get(i); String semester = fileContents.get(3).get(i); String courseType = fileContents.get(4).get(i); addData(course, credit, score, semester, courseType); this.courses.add(new Course(course, score, credit, semester, courseType)); } JOptionPane.showMessageDialog(null, "Data has been imported"); }代码经常返回异常,请优化这个代码,使数据可以正确从txt文件中读取
时间: 2023-06-27 08:08:32 浏览: 201
这段代码有几个问题需要优化:
1. 如果其中一个文件读取失败,整个方法就会返回并且数据无法正确导入,应该在每个文件读取失败后继续读取其他文件。
2. 在读取文件时,最好使用绝对路径,因为相对路径可能会因为不同的执行环境而不同。
3. 在解析文件内容时,最好检查文件内容的行数是否相等,否则会导致数据不匹配。
以下是优化后的代码:
```
public void importData() {
List<String> files = Arrays.asList("courses.txt", "scores.txt", "credits.txt", "semesters.txt", "types.txt");
List<List<String>> fileContents = new ArrayList<>();
for (String file : files) {
try (Stream<String> stream = Files.lines(Paths.get("F:/ProgramData/IdeaProjects/BUPT-EBU6304G49-main/SE0514/src/data/" + file), StandardCharsets.UTF_8)) {
fileContents.add(stream.collect(Collectors.toList()));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Failed to import data from file: " + file);
}
}
if (fileContents.size() != 5) {
JOptionPane.showMessageDialog(null, "Failed to import data");
return;
}
// Check if each file has the same number of lines
int numLines = fileContents.get(0).size();
for (List<String> content : fileContents) {
if (content.size() != numLines) {
JOptionPane.showMessageDialog(null, "Failed to import data: files do not have the same number of lines");
return;
}
}
// Clear current data
this.courses.clear();
// Read data from files and add to list
for (int i = 0; i < numLines; i++) {
String course = fileContents.get(0).get(i);
String score = fileContents.get(1).get(i);
String credit = fileContents.get(2).get(i);
String semester = fileContents.get(3).get(i);
String courseType = fileContents.get(4).get(i);
addData(course, credit, score, semester, courseType);
this.courses.add(new Course(course, score, credit, semester, courseType));
}
JOptionPane.showMessageDialog(null, "Data has been imported");
}
```
阅读全文