[英]How to save lines from a text file using buffered reader
所以我有一个文本文件,其中包含有关课程的一些信息,例如课程 CRN、课程全名、课程描述、课程学分。 文件中还有更多这样的课程,每行 4 行,以新行分隔。 我需要将每一行保存到一个字符串中,以便稍后传递给构造函数,这样我就可以将它们存储在 hashmap 中。 同样在每一行之后,它会知道一个新的课程信息已经开始。 但我不太熟悉缓冲阅读器来做到这一点。 到目前为止,我只有它可以读取每行 output 但我需要保存每一行(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
感谢您的帮助对不起,如果我解释的东西不好,这里的第一个问题
编辑:是的,我已经定义了课程 class,其中包含所有 getter 和 setter 以及适当的字段。
也许您可以尝试以下方法。
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
读取文本文件并将内容存储到 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.