將文字檔案讀取到 Java HashMap 中
HashMap 是一個用於實現 Map 介面的類。它以鍵值對的形式儲存其元素。鍵是一個用於獲取和接收與其關聯的值的物件。它可以訪問 Map 介面的所有方法,但它本身沒有任何額外的方法。不允許重複的值,儘管我們可以儲存空值和鍵。在本文中,我們將嘗試將本地文字檔案的內容讀取到 Java HashMap 中。
將文字檔案讀取到 Java HashMap 中的 Java 程式
HashMap 的一般語法如下:
語法
HashMap<TypeOfKey, TypeOfValue> nameOfMap = new HashMap<>();
我們的第一個任務是建立一個文字檔案(副檔名:.txt),並根據您的選擇命名。將以下內容新增到您的檔案中:
Milk:55 Bread:15 Rice:65 Egg:20
您檔案的格式必須與上述文字相同。
方法
匯入“java.util”包以啟用 HashMap 類的使用,並匯入“java.io”用於檔案輸入/輸出。
將檔案的位置儲存在 String 型別變數中。
建立一個返回型別為 Map 的方法,以讀取並以 HashMap 的形式返回文字檔案的內容。
在此方法內部,建立一個 HashMap 並定義一個 try 和 catch 塊,以便我們可以處理“FileNotFoundException”和“IOException”。
現在,在 try 塊中將檔案路徑儲存在“File”類物件中,然後使用“BufferedReader”類物件讀取檔案內容。
使用內建方法“readLine()”讀取檔案的所有內容,並使用“:”作為分隔符將內容拆分為多個部分。
在 if 塊中,我們將檢查“item”和“price”的值是否為空。如果它不為空,則使用“put()”方法將值儲存在 Map 中。
在 main() 方法內部,建立一個新的 Map,並透過呼叫方法“copyFile()”將返回的值儲存在其中。
使用“getKey()”和“getValue()”方法,我們將檢索並列印詳細資訊。
示例
import java.io.*; import java.util.*; public class ReadTxt { final static String sharePath = "D:/Java Programs/Map content.txt"; // method to copy file public static Map<String, Integer> copyFile() { // Create a map HashMap<String, Integer> getInfo = new HashMap<String, Integer>(); try { // store the file path in file object File filename = new File(sharePath); // BufferedReader object of given File BufferedReader bufrd = new BufferedReader( new FileReader(filename) ); // to store content of file String info = null; // reading the given file while ( (info = bufrd.readLine()) != null ){ // spliting each line of content by delimiter String[] values = info.split(":"); // first part is item and second is price String item = values[0].trim(); // convert string price to integer Integer price = Integer.parseInt( values[1].trim() ); // storing content to hash map if( !item.equals("") && !price.equals("") ) getInfo.put(item, price); } } catch(Exception exp) { // to handle the exception System.out.println(exp); } return getInfo; // return result } public static void main(String[] args) { // copying content to new map Map<String, Integer> newMap = copyFile(); // to print the details for(Map.Entry<String, Integer> print : newMap.entrySet()) { System.out.println( print.getKey() + " : " + print.getValue() ); } } }
輸出
Egg : 20 Milk : 55 Bread : 15 Rice : 65
結論
HashMap 類和 Map 介面是集合框架的一部分。集合允許將物件組合到一個單元中。在本文中,我們首先定義了 HashMap 類,然後討論了一個將文字檔案讀取到 Java HashMap 中的 Java 程式。