- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reading Text File into Java HashMap
HashMap is a class that is used to implement Map Interface. It stores its element in key-value pairs. The Key is an object that is used to fetch and receive value associated with it. It has access to all the methods of Map Interface, it does not have any additional methods of its own. Duplicate values are not allowed, although we can store null values and keys. In this article, we will try reading the content of a local text file into Java HashMap.
Java Program to Read Text File into Java HashMap
The general syntax for HashMap is as follows −
Syntax
HashMap<TypeOfKey, TypeOfValue> nameOfMap = new HashMap<>();
Our first task is to create a text file (extension: .txt) with any suitable name of your choice. Add the following content to your file −
Milk:55 Bread:15 Rice:65 Egg:20
The formating of your file must be same as the above text.
Approach
Import the ‘java.util’ package to enable the use of HashMap class and ‘java.io’ for file input /output.
Store the location of your file in a String type variable.
Create a method of return type Map to read and return the content of text file in the form of HashMap.
Inside this method, create a HashMap and define a try and catch block so that we can handle the ‘FileNotFoundException’ and ‘IOException’.
Now, in try block store the path of file in a ‘File’ class object and then using the object of ‘BufferedReader’ class, read the content of file.
Take a while loop that will read all the content of file using the built-in method ‘readLine()’ and also we will split the content into parts using ‘:’ as a delimiter.
In the if block, we will check whether the value of ‘item’ and ‘price’ is empty or not. If it is not empty, store the values in the Map using ‘put()’ method.
Inside the main() method, create a new Map and store the returned values in it by calling the method ‘copyFile()’.
Using the ‘getKey()’ and ‘getValue()’ methods, we will retrieve and print the details.
Example
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() ); } } }
Output
Egg : 20 Milk : 55 Bread : 15 Rice : 65
Conclusion
The HashMap Class and the Map Interface are part of the Collection Framework. The collection allows the grouping of objects in a single unit. In this article, we started by defining the HashMap class and then we discussed a Java program to read a text file into Java HashMap.