Java 将文本文件读入HashMap

Java 将文本文件读入HashMap

HashMap是用于实现Map接口的类。它以键值对的形式存储元素。键是用于获取与其关联的值的对象。它可以访问Map接口的所有方法,但没有自己的附加方法。不允许重复值,尽管可以存储空值和键。在本文中,我们将尝试将本地文本文件的内容读入Java HashMap中。

Java程序读取文本文件到Java HashMap中

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()”和使用”:”作为分隔符,获取一个读取文件内容的while循环。

  • 在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程序。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程