如何使用缓冲 reader 从文本文件中保存行

How to save lines from a text file using buffered reader

所以我有一个文本文件,其中包含一些关于课程的信息,例如课程 CRN、课程全名、课程描述、课程学分。 文件中还有很多这样的课程,每行 4 行,中间用新行分隔。我需要将每一行保存到一个字符串中,以便稍后传递给构造函数,这样我就可以将它们存储在哈希图中。同样在每一行之后,它会知道一个新的课程信息已经开始。但是我不太熟悉缓冲 reader 来做到这一点。到目前为止,我只有它可以读取和输出每一行,但我需要保存每一行(CRN 到 CRN,名称到名称等) 这是我目前所拥有的:

有问题的方法:

public void addCourses() {
        String sb;
        try(BufferedReader br = new BufferedReader(new FileReader("testC.txt"))) {
            while((sb = br.readLine()) != null) {  
                System.out.println(sb); //just prints out all lines identical to text file
                //Do stuff here?
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

文本文件看起来像这样:

MAT205 
Discrete Mathematics 
description here 
4.0

MAT210 
Applied Linear Algebra 
description here 
3.0 

...and so on

感谢您的帮助,如果我解释的不好,请在此处提出第一个问题

编辑:是的,我已经定义了一个包含所有 getter 和 setter 以及适当字段的课程 class。

也许你可以试试下面的方法。

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();
    }

我假设您已经有一个 POJO 课程,如下所示:

class Course {
    private String crn;
    private String name;
    private String description;
    private String credit;

    //general getters and setters 
}

然后下面的示例代码显示了如何使用BufferedReader读取文本文件并将内容存储到集合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
}