我有这种形式的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>...

最佳答案

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]);
}

09-30 15:19
查看更多