我对Java很陌生,我正在做一个项目。有人告诉我,为了完成这个项目,我需要将文件保存到哈希图中。这个文件包含单词及其缩写,所以以后我希望能够搜索一个特定的单词,然后返回它的缩写。我已经能够制作哈希映射并访问该文件,但我无法将其保存到哈希映射中。
public Shortener() {
Map<String, String> abbrevFile = new HashMap<String, String>();
File file = new File("C:\abbreviations.txt");
我会使用属性文件,因为它是一种现有格式。
例如
Hello=Hi
Abreviation=Abr
如
Properties p = new Properties();
p.load(file);
abbrevFile.putAll((Map) p);
要查找地图,您可以这样做
public String lookup(String word) {
return abbrevFile.get(word);
}
下面是读取文件并将数据存储在哈希图中的示例
static HashMap<String, String> wordList = new HashMap<>();
public static void main(String[] args) {
readFile(new File("words.txt"));
}
private static void readFile(File file) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split("-");
wordList.put(args[0], args[1]);
}
System.out.println("Populated list with "+ wordList.size() + " words.");
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
提供以下格式
word-abbreviation
word-abbreviation
word-abbreviation