📜  将文本文件读入Java HashMap

📅  最后修改于: 2022-05-13 01:54:48.953000             🧑  作者: Mango

将文本文件读入Java HashMap

我们将研究允许我们从文件中读取 HashMap 文本的方法或我们如何反序列化文件

反序列化:这里我们正在从序列化文件中复制 HashMap 对象及其内容。

方法:

首先方法/函数HashMapFromTextFile将有方法 bufferedReader读取文本文件的行并插入到地图中,然后返回地图

bf = new BufferedWriter( new FileWriter(file_name) );
  • 首先我们调用BufferedReader来读取每一行。
  • 在每一行,我们都有键值对。所以,现在用“:”分割它,同时把键和值放到地图上
  • 并返回地图
Java
// Java program to reading
// text file to HashMap
  
import java.io.*;
import java.util.*;
  
class GFG {
    final static String filePath
        = "F:/Serialisation/write.txt";
    public static void main(String[] args)
    {
  
        // read text file to HashMap
        Map mapFromFile
            = HashMapFromTextFile();
  
        // iterate over HashMap entries
        for (Map.Entry entry :
             mapFromFile.entrySet()) {
            System.out.println(entry.getKey() + " : "
                               + entry.getValue());
        }
    }
  
    public static Map HashMapFromTextFile()
    {
  
        Map map
            = new HashMap();
        BufferedReader br = null;
  
        try {
  
            // create file object
            File file = new File(filePath);
  
            // create BufferedReader object from the File
            br = new BufferedReader(new FileReader(file));
  
            String line = null;
  
            // read file line by line
            while ((line = br.readLine()) != null) {
  
                // split the line by :
                String[] parts = line.split(":");
  
                // first part is name, second is number
                String name = parts[0].trim();
                String number = parts[1].trim();
  
                // put name, number in HashMap if they are
                // not empty
                if (!name.equals("") && !number.equals(""))
                    map.put(name, number);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
  
            // Always close the BufferedReader
            if (br != null) {
                try {
                    br.close();
                }
                catch (Exception e) {
                };
            }
        }
  
        return map;
    }
}