Java 读取文本文件存储到 HashMap

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 的建议非常有效,我们可以使用 List 来跟踪将键添加到 Map 的顺序。但是有一种数据结构支持这种能力:

我假设您希望键值类似于 (test1,get1)、(test2,get2) 等。您的代码首先将 (test1,null)、(test2,null) 等放入 HashMap。当您到达检查点时,您需要知道添加到 HashMap 的第一个条目是什么,以便将其值设置为 checkpoint.Now 之后的第一行,您的问题是准确检索 HashMap 中的键值按照它们在地图中的顺序更新它们的值。这在 HashMap 中是不可能的。相反,您可以使用支持此类功能的 LinkedHashMap