public void importData() { try { List<String> courses = Files.readAllLines(Paths.get("data/courses.txt"), StandardCharsets.UTF_8); List<String> scores = Files.readAllLines(Paths.get("data/scores.txt"), StandardCharsets.UTF_8); List<String> ids = Files.readAllLines(Paths.get("data/credits.txt"), StandardCharsets.UTF_8); List<String> semesters = Files.readAllLines(Paths.get("data/semesters.txt"), StandardCharsets.UTF_8); List<String> courseTypes = Files.readAllLines(Paths.get("data/types.txt"), StandardCharsets.UTF_8); this.courses.clear(); for (int i = 0; i < courses.size(); i++) { String course = courses.get(i); String id = ids.get(i); String score = scores.get(i); String semester = semesters.get(i); String courseType = courseTypes.get(i); addData(course,id,score,semester,courseType); Course student = new Course(course, score,id, semester, courseType); this.courses.add(student); //updateDisplay(); } //updateDisplay(); JOptionPane.showMessageDialog(null, "Data has been imported"); } catch (IOException e) { JOptionPane.showMessageDialog(null, "An error occurred importing data"); } }优化这个代码
时间: 2023-07-15 22:11:45 浏览: 155
可以优化的几个方面:
1. 将重复的文件读取操作提取成一个方法,避免代码重复。
2. 使用 try-with-resources 语句来自动关闭资源,避免忘记关闭资源导致的资源泄漏。
3. 在 for 循环中,可以使用更简洁的 foreach 循环。
4. 在 for 循环中,不必要地创建了一个 Course 对象,可以直接调用 addData 方法添加数据。
优化后的代码如下:
```
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("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 id = fileContents.get(2).get(i);
String score = fileContents.get(1).get(i);
String semester = fileContents.get(3).get(i);
String courseType = fileContents.get(4).get(i);
addData(course, id, score, semester, courseType);
this.courses.add(new Course(course, score, id, semester, courseType));
}
JOptionPane.showMessageDialog(null, "Data has been imported");
}
```
阅读全文