首页 > 解决方案 > 读取txt文件到hashmap,用“\t”分割

问题描述

我有一个带有这种形式的 txt 文件:

 1     01/01/2018 01:00 1915    8,4
 1     01/01/2018 02:00 2111    8,8

读取文件后,我想将其存储到具有此结构的 Map 中:

     <"Key1",1> <"Key2",01/01/2018 01:00>  <"Key3",1915>  <"Key4",8,4>

这是导入代码

        BufferedReader buf = new BufferedReader(new 
 FileReader("test.txt"));
        ArrayList<String> words = new ArrayList<>();
        String lineJustFetched = null;
        String[] wordsArray;
        Map<String,String> map = new HashMap<>();

        while(true){
            lineJustFetched = buf.readLine();
            if(lineJustFetched == null) {
                break;
            } else {
                wordsArray = lineJustFetched.split("\t");
                for(String each : wordsArray){
                        words.add(each);
                  //  System.out.println(words.toString());
                    map.put("Key1",each);
                    System.out.println(map.toString());

                }
            }
        }
        buf.close();

我不知道要在地图中放入什么才能拥有这种结构的问题

   <"Key1",1> <"Key2",01/01/2018 01:00>...

标签: java

解决方案


for与索引一起使用

for(int i = 0 ; i < wordsArray.length ; i++) {
    map.put("Key"+(i+1), wordsArray[i]);
}

编辑

在评论之后,您可以设置一个带有字段名称的数组并使用它

String[] fieldNames = {"id", "date", "whatever"};
for(int i = 0 ; i < wordsArray.length ; i++) {
    map.put(fieldNames[i], wordsArray[i]);
}

推荐阅读