2 回答
TA贡献1829条经验 获得超4个赞
我假设您已经有一个 POJO 课程,如下所示:
class Course {
private String crn;
private String name;
private String description;
private String credit;
//general getters and setters
}
然后以下示例代码展示了如何使用BufferedReader读取文本文件并将内容存储到 Collection 中List<Course>。
List<Course> courses = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get("testC.txt"))) {
String line;
Course course = new Course();
while ((line = br.readLine()) != null) {
if (!line.trim().isEmpty()) {
if (course.getCrn() == null) {
course.setCrn(line.trim());
} else if (course.getName() == null) {
course.setName(line.trim());
} else if (course.getDescription() == null) {
course.setDescription(line.trim());
} else {
course.setCredit(line.trim());
courses.add(course);
}
} else {
course = new Course();
}
}
} catch (IOException e) {
//TODO exception handling
}
TA贡献1878条经验 获得超4个赞
也许你可以尝试下面的方法。
String sb;
try(BufferedReader br = new BufferedReader(new FileReader("kmh.txt"))) {
int count = 0;
while((sb = br.readLine()) != null) {
// System.out.println(sb); //just prints out all lines identical to text file
if(!sb.isEmpty()){
String courseCRN = null;
String courseFullName = null;
String courseDescription = null;
String courseCredits = null;
if(count == 0) courseCRN = sb;
if(count == 1) courseFullName = sb;
if(count == 2) courseDescription = sb;
if(count == 3) courseCredits = sb;
count++;
//Save your course data in map
}
if(count == 4) count = 0;
}
} catch(Exception e) {
e.printStackTrace();
}
添加回答
举报