[英]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.