![](/img/trans.png)
[英]Java: When reading a text file, how can i read that specific line which contains a certain string?
[英]How do I read in a file such that for each line that contains a certain string, save the lines underneath to a HashMap?
我承認這可能是一個簡單的問題,但我似乎無法思考 map。 假設我有一個 .txt 文件,我正在使用 Java 中的 BufferedReader 讀取該文件,該文件可能如下所示:
Category: Dairy
Yogurt
Cheese
Butter
Category: Vegetables
Carrots
Cucumbers
Category: Snacks
Granola Bars
Trail Mix
Chips
Candy
Pop Tarts
例如,我想創建一個 HashMap,稱為雜貨,將 map 項目歸入其各自的類別。 例如:
groceries.put("item", "category");
如何以跟蹤哪個項目屬於哪個類別的方式讀取此文件,以便以有意義的方式將其放入 HashMap 中? 這是我迄今為止嘗試過的大致想法。 (我最初嘗試使用 ArrayLists 但發現 HashMaps 可能比 map 數據更好)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("Category")){
(save in an arrayList() called Category)
}
else{
(save in arrayList() called Item)
}
}
同樣,這正是我最初嘗試過的。 讓我知道是否需要進一步澄清。
這可以啟發(在任何人關閉它之前):您要構建的結構是 map(鍵值結構)而不是列表。
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)));
String line;
String currentCategory = "";
Map<String, String> groceries = new HashMap<>();
while ((line = in.readLine()) != null) {
if (line.startsWith("Category: ")) {
currentCategory = line.substring(10);
} else {
groceries.put(line, currentCategory);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.