java 将文本文件中的值存储到地图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5701832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
store values from text file into map
提问by Pranay
How do I read strings from a text file and store in a hashmap? File contains two columns.
如何从文本文件中读取字符串并存储在哈希图中?文件包含两列。
File is like:
文件是这样的:
FirstName LastName
Pranay Suyash and so on...
名字姓氏
Pranay Suyash 等等...
回答by aioobe
Here's one way:
这是一种方法:
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileReader("filename.txt"));
HashMap<String, String> map = new HashMap<String, String>();
while (scanner.hasNextLine()) {
String[] columns = scanner.nextLine().split(" ");
map.put(columns[0], columns[1]);
}
System.out.println(map);
}
}
Given input:
给定输入:
somekey somevalue
someotherkey someothervalue
this prints
这打印
{someotherkey=someothervalue, somekey=somevalue}
If your lines look differently, I either suggest you fetch columns[0]
and columns[1]
and do your string manipulation as needed, or, if you're comfortable with regular expressions, you could use Pattern
/ Matcher
to match the line against a pattern and get the content from the capture groups.
如果您的行看起来不同,我建议您根据需要获取columns[0]
和columns[1]
执行字符串操作,或者,如果您对正则表达式感到满意,则可以使用Pattern
/Matcher
将行与模式匹配并从捕获组中获取内容.
回答by Andreas Dolk
Just in case
以防万一
- your keys (first column) don'tcontain spaces and
- your columns are separated by either a
:
, a=
or a white char (except newline)
- 您的键(第一列)不包含空格和
- 您的列由 a
:
、 a=
或白色字符分隔(换行符除外)
then this may work:
那么这可能有效:
Map<Object, Object> map = new Properties();
((Properties) map).load(new FileReader("inputfile.txt"));
Just saw your sample input... You shouldn't put thatdata in a map, unless it is guaranteed that allfirstnames are unique.
刚刚看到您的示例输入...您不应该将该数据放入地图中,除非保证所有名字都是唯一的。
Otherwise this will happen:
否则会发生这种情况:
map.put("Homer", "Simpson"); // new key/value pair
map.put("Bart", "Simpson"); // new key/value pair
map.put("Homer", "Johnsson"); // value for "Homer" is replaced with "Johnsson"
System.out.println(map.get("Homer")); // guess what happens..
回答by Ammu
In the hash map if you want to map each row in the two columns you can make the first column value as the key and the second column as the value. But the keys should be unique in the Hashmap. If the first column values are unique you can go for the following approach
在哈希映射中,如果要映射两列中的每一行,可以将第一列值作为键,将第二列作为值。但是键在 Hashmap 中应该是唯一的。如果第一列值是唯一的,您可以采用以下方法
Map<String,String> map = new HashMap<String,String>();
map.put(firstColVal,secondColVal);