在写代码的时候,当鼠标悬浮在某一个单词上面的时候,有道词典点有时会弹出一个消息气泡,在里面中给出关于这个单词相关的解释,下面给大家展示一个使用Java基础语言编写的英汉字典案例: 实现功能: 输入英文,给出对应的中文翻译,如果没有这个单词没有被收录会有相关提示 代码编写环境 JDK:1.8.0_191 Eclipse:2019-03 (4.11.0) 素材: dict.txt 字典资源文本文件,保存一些下列格式的文件,英文和翻译之间用制表符隔开: Africa n. 非洲 Aids n. 爱滋病 America n. 美洲 April n. 四月 案例实现用到的技术: IO流 Map—HashMap 字符串分割 异常处理 代码思路 1、 根据字典文件路径,创建file对象 2、 判断file对象是否为空,不为空就继续,否则直接返回null 3、 File不为空,创建InputStreamReader和BufferedReader对象 4、 循环读取字典文本中的内容,切割得到数组,保存在map中 5、 提示输入单词,查询单词,输出查询结果 运行效果 开始运行的提示: ![]() 查询成功的反馈 ![]() 单词不存在的反馈 ![]() 案例代码: 编写方法读取文本中的内容 package com.feng.demo01; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * 英汉字典案例 * @author dushine */ public class GetDict { public static void main(String[] args) { String path = "E:\\dict.txt"; // 获取字典中的所有内容 Map<String, String> dict = getText(path); // 判断字典是否为空,提示输入单词,获取查询结果 if (dict != null) { @SuppressWarnings("resource") // 获取输入内容 Scanner input = new Scanner(System.in); System.out.println("请输入要查询的单词:"); String word = input.next(); // 查询字典获取中文,如果没有也给出反馈 String ret = dict.get(word); if (ret != null) { System.out.println("查询结果:\n"+word + ":" + ret); } else { System.out.println("您查询的单词尚未收录,敬请期待!"); } } } /** * 获取字典文件中内容 * @param path * @return */ private static Map<String, String> getText(String path) { // 可能会出现异常 try { // 根据路径创建文件对象 File file = new File(path); // 判断路径指向的文件是否存在 if (file.exists() && file.isFile()) { // 创建map,存储读取得到的内容 Map<String, String> dict = new HashMap<String, String>(); System.out.println("文件路径正确,正在解析。。。"); // 创建输入流对象 InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "gbk"); BufferedReader bufferedReader = new BufferedReader(reader); String text = null; // 循环读取文件内容 while ((text = bufferedReader.readLine()) != null) { // 切割每一行内容,得到数组 String[] arr = text.split("\t"); // 把切割得到的内容放入map dict.put(arr[0], arr[1]); } // 读取结束,关闭流对象并返回结果 reader.close(); return dict; } else { System.out.println("字典崩溃啦,下次再来使用吧。。。"); } } catch (Exception e) { System.out.println("字典好像出了点问题、文件内容出错啦。。。"); e.printStackTrace(); } // 路径指向的不是文件或者文件不存在返回null return null; } } |
|
来自: 好程序员IT > 《Java培训教程》