这是一种方式:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
给定输入:
somekey somevalue
someotherkey someothervalue
Run Code Online (Sandbox Code Playgroud)
这打印
{someotherkey=someothervalue, somekey=somevalue}
Run Code Online (Sandbox Code Playgroud)
如果你的行看起来不一样,我建议你提取columns[0]并columns[1]根据需要进行字符串操作,或者,如果你对正则表达式感到满意,你可以使用Pattern/ Matcher来匹配模式的行并从捕获组中获取内容.