[英]Java read text file store to HashMap
我只是想知道這種邏輯是否可行,我想做的是逐行讀取文本文件並將其存儲到HashMap。 我想將前4行存儲到hashMap的鍵中,當這些行讀取檢查點時,下一行將存儲為HashMap的值。
File file1 = new File("C:\test\testfolder\test.txt");
HashMap<String,String> hashMap = new HashMap();
String check = "checkpointone";
try{
LineIterator it = FileUtils.lineIterator(file1,"UTF-8");
String line;
while(it.hasNext()){
line = it.nextLine();
hashMap.put(line , null);
if(line.contains(check)){
//do the logic here
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
test.txt數據:
test1
test2
test3
test4
checkpointone
get1
get2
get3
get4
將檢查點之前的行存儲在列表中。 在檢查點之后,使用列表中的每個項目作為鍵,將每一行插入到哈希圖中。
...
boolean pastCheckpoint = false;
int keyIndex = 0;
// We will store keys in here
List<String> keys = new ArrayList<String>();
while(it.hasNext()){
line = it.nextLine();
if (line.contains(check)) {
// We don't actually want to store this line,
// so just set the flag
pastCheckpoint = true;
}
else if (pastCheckpoint) {
// We must already have a key defined
// Get that key and increment the counter for next time
hashMap.put(keys.get(keyIndex++), line);
}
else {
// We're not past the checkpoint so save this key for later
keys.add(line);
}
}
...
請注意,這將無法處理輸入文件格式錯誤的情況(例如,值多於鍵將導致IndexOutOfBoundsException)。
這種邏輯是可能的。 但是,迭代器及其子類不具有contain()
函數。
它應該是
if(hashMap.contains(check))
然后,如果您打算這樣做,則可以在到達檢查點后退出循環。 否則,您可以讓循環繼續進行。
@deyur提出的建議效果很好,我們可以使用列表來跟蹤向地圖添加鍵的順序。 但是有一個支持這種功能的數據結構:
我假設您希望鍵值像(test1,get1),(test2,get2)等。您的代碼首先將(test1,null),(test2,null)等放入HashMap中。 到達檢查點時,您需要知道添加到HashMap的第一個條目是什么,以便將其值設置為檢查點之后的第一行。現在,您的問題是要在HashMap中准確地檢索鍵值。與它們在地圖中的排列順序相同,並更新其值。 在HashMap中這是不可能的。 相反,您可以使用支持這種功能的LinkedHashMap 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.