将文本文件读取到 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 程序。

更新于: 2023年5月16日

2K+ 阅读量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.