因此,我有一个文本文件,其中包含有关课程的一些信息,例如课程CRN,课程全名,课程说明,课程学分。文件中还有更多类似的课程,每行4行,中间用新行分隔。我需要将每一行保存为一个字符串,以便以后传递给构造函数,以便将它们存储在哈希图中。同样,在每条新行之后,它将知道新的课程信息已经开始。但是我对缓冲的读者并不十分熟悉。到目前为止,我只能读取和输出每一行,但是我需要保存每一行(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
感谢您的帮助,如果我在解释不好的东西,这里是第一个问题
编辑:是的,我已经有一个定义的Course类,其中包含所有getter和setter以及适当的字段。
我假设您已经有一个课程的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
}
也许您可以尝试以下方法。
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();
}