Java用map实现背单词功能并实现增删查map储存在文件中
时间: 2024-05-06 07:17:28 浏览: 196
以下是Java代码实现背单词功能并使用Map实现增删查,并将Map储存在文件中:
```java
import java.io.*;
import java.util.*;
public class WordBook {
private Map<String, String> wordMap;
private String fileName;
public WordBook(String fileName) {
this.fileName = fileName;
wordMap = new HashMap<>();
loadWords();
}
public void addWord(String word, String meaning) {
wordMap.put(word, meaning);
saveWords();
}
public void deleteWord(String word) {
wordMap.remove(word);
saveWords();
}
public String getMeaning(String word) {
return wordMap.get(word);
}
public void listAllWords() {
System.out.println("Word\tMeaning");
for (Map.Entry<String, String> entry : wordMap.entrySet()) {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
private void loadWords() {
try {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
wordMap = (Map<String, String>) ois.readObject();
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
// 如果文件不存在或读取失败,忽略错误,使用空的Map
}
}
private void saveWords() {
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(wordMap);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
WordBook wordBook = new WordBook("wordbook.dat");
while (true) {
System.out.println("请选择操作:1.添加单词 2.删除单词 3.查找单词 4.列出所有单词 5.退出");
int option = scanner.nextInt();
scanner.nextLine();
switch (option) {
case 1:
System.out.println("请输入单词:");
String word = scanner.nextLine();
System.out.println("请输入意思:");
String meaning = scanner.nextLine();
wordBook.addWord(word, meaning);
System.out.println("添加成功!");
break;
case 2:
System.out.println("请输入要删除的单词:");
word = scanner.nextLine();
wordBook.deleteWord(word);
System.out.println("删除成功!");
break;
case 3:
System.out.println("请输入要查找的单词:");
word = scanner.nextLine();
meaning = wordBook.getMeaning(word);
if (meaning == null) {
System.out.println("未找到该单词!");
} else {
System.out.println("意思是:" + meaning);
}
break;
case 4:
wordBook.listAllWords();
break;
case 5:
System.exit(0);
default:
System.out.println("无效操作,请重新选择!");
break;
}
}
}
}
```
这里使用了Java的序列化机制将Map对象储存在文件中。需要注意的是,如果Map对象中的值不支持序列化,或者Map对象本身不能被序列化(例如使用了某些特殊的Map实现),则无法使用这种方式储存Map对象。此时可以使用其它方式,例如将Map对象转换成JSON字符串储存,或者使用数据库等。
阅读全文