java - 读取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>...
解决方案
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]);
}
推荐阅读
- firebase - 我在使用 firebase 的 android studio 中遇到问题
- azure - Blob 存储帐户的 Azure SAS 令牌不起作用
- jupyter-notebook - 我可以像 Google Colab 一样使用 AWS Sagemaker 吗?
- python - 通过 Selenium 导航下载课程列表
- python - 处理 Brownie FundMe Chainlink 演示和与合约交互的脚本在 Rinkeby 上工作,但不在 Ganache
- tensorboard - 将 Google 的 Tensorboard 连接到 Vertex AI AutoML
- arrays - 是否可以编写一个以整数数组作为参数并返回 C 中数组元素数的函数
- eclipse - Maven 构建无法正确生成文件(War and Ear)
- pytorch - 如何恢复和使用经过训练的 tacotron2 模型
- python - Python:使用 PIL 和 setpalette() 替换图像颜色时出错