如何从文本文件中读取字符串并将其存储在 HashMap 中? 文件包含两列。
文件如下:
名姓
Pranay Suyash 等...
最佳答案
这是一种方法:
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);
}
}
给定输入:
somekey somevalue
someotherkey someothervalue
这打印
{someotherkey=someothervalue, somekey=somevalue}
如果您的行看起来不同,我建议您获取 columns[0]
和 columns[1]
并根据需要进行字符串操作,或者,如果您如果您熟悉正则表达式,您可以使用 Pattern
/Matcher
将行与模式匹配并从捕获组中获取内容。
关于java - 将文本文件中的值存储到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5701832/