在寫代碼的時候,當鼠標懸浮在某一個單詞上面的時候,有道詞典點有時會彈出一個消息氣泡,在里面中給出關(guān)于這個單詞相關(guān)的解釋,下面給大家展示一個使用Java基礎(chǔ)語言編寫的英漢字典案例: 實現(xiàn)功能: 輸入英文,給出對應的中文翻譯,如果沒有這個單詞沒有被收錄會有相關(guān)提示 代碼編寫環(huán)境 JDK:1.8.0_191 Eclipse:2019-03 (4.11.0) 素材: dict.txt 字典資源文本文件,保存一些下列格式的文件,英文和翻譯之間用制表符隔開: Africa n. 非洲 Aids n. 愛滋病 America n. 美洲 April n. 四月 案例實現(xiàn)用到的技術(shù): IO流 Map—HashMap 字符串分割 異常處理 代碼思路 1、 根據(jù)字典文件路徑,創(chuàng)建file對象 2、 判斷file對象是否為空,不為空就繼續(xù),否則直接返回null 3、 File不為空,創(chuàng)建InputStreamReader和BufferedReader對象 4、 循環(huán)讀取字典文本中的內(nèi)容,切割得到數(shù)組,保存在map中 5、 提示輸入單詞,查詢單詞,輸出查詢結(jié)果 運行效果 開始運行的提示: ![]() 查詢成功的反饋 ![]() 單詞不存在的反饋 ![]() 案例代碼: 編寫方法讀取文本中的內(nèi)容 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"; // 獲取字典中的所有內(nèi)容 Map<String, String> dict = getText(path); // 判斷字典是否為空,提示輸入單詞,獲取查詢結(jié)果 if (dict != null) { @SuppressWarnings("resource") // 獲取輸入內(nèi)容 Scanner input = new Scanner(System.in); System.out.println("請輸入要查詢的單詞:"); String word = input.next(); // 查詢字典獲取中文,如果沒有也給出反饋 String ret = dict.get(word); if (ret != null) { System.out.println("查詢結(jié)果:\n"+word + ":" + ret); } else { System.out.println("您查詢的單詞尚未收錄,敬請期待!"); } } } /** * 獲取字典文件中內(nèi)容 * @param path * @return */ private static Map<String, String> getText(String path) { // 可能會出現(xiàn)異常 try { // 根據(jù)路徑創(chuàng)建文件對象 File file = new File(path); // 判斷路徑指向的文件是否存在 if (file.exists() && file.isFile()) { // 創(chuàng)建map,存儲讀取得到的內(nèi)容 Map<String, String> dict = new HashMap<String, String>(); System.out.println("文件路徑正確,正在解析。。。"); // 創(chuàng)建輸入流對象 InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "gbk"); BufferedReader bufferedReader = new BufferedReader(reader); String text = null; // 循環(huán)讀取文件內(nèi)容 while ((text = bufferedReader.readLine()) != null) { // 切割每一行內(nèi)容,得到數(shù)組 String[] arr = text.split("\t"); // 把切割得到的內(nèi)容放入map dict.put(arr[0], arr[1]); } // 讀取結(jié)束,關(guān)閉流對象并返回結(jié)果 reader.close(); return dict; } else { System.out.println("字典崩潰啦,下次再來使用吧。。。"); } } catch (Exception e) { System.out.println("字典好像出了點問題、文件內(nèi)容出錯啦。。。"); e.printStackTrace(); } // 路徑指向的不是文件或者文件不存在返回null return null; } } |
|
來自: 好程序員IT > 《Java培訓教程》