首页 > 解决方案 > 将文件中的数据读入HashMap的方法

问题描述

我需要写一个方法,从文件中读取数据到HashMap中,key是文件的行号,value是行中的文本。并且只有 HashMap 值,其键是 2 的幂,必须写入另一个文件。

我现在用一首诗创建了一个文件。编写了一种读取文件的方法,该文件在 ArrayList 中打印文本。运行一个循环并获取行号和文本会很方便。但我不太明白下一步该做什么。

public static void main(String[] args) throws IOException {

    List<String> fileToRead = FileWriterReader.ourFileReaderToList("HAMLET.txt");
    System.out.println(fileToRead);

    public static List<String> ourFileReaderToList(String fileToRead) throws FileNotFoundException {
        File file = new File(fileToRead);

        List<String> poemLines = new ArrayList<String>();
        Scanner in = null;
        try {
            if (file.exists()) {
                in = new Scanner(file);
                while (in.hasNextLine()) {
                    poemLines.add(in.nextLine());
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return poemLines;
    }

    public static void ourWriterListToFile(String fileToWrite, List<String> listToWrite) throws IOException {
        FileWriter fw = new FileWriter(fileToWrite, true);
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(fw);
            int k = 0;
            for (String s : listToWrite) {
                if (k == (listToWrite.size() - 1)) {
                    bw.write(s);
                } else {
                    bw.write(s + "\n");
                }
                k++;

            }
        } finally {
            bw.close();
            fw.close();
        }
    }

    public static void parsedFile(List<String> listFromFile) {
        for (String s : listFromFile)
            System.out.println(s);

    }
}

标签: javahashmap

解决方案


您当然可以使用循环将 ArrayList 转换为 HashMap。由于该ourFileReaderToList函数创建的 ArrayList 分别按顺序存储每一行​​,因此可以使用另一个函数从 List 中读取值并计算行号是多少。

例如:

HashMap listToHashMap(List<String> list) {
    HashMap<Integer, String> poemmap = new HashMap<Integer, String>();    //Our hashmap
    int linenumber = 0;    //Variable to keep track of the line number

    for (String line : list) {
         poemmap.put(linenumber, line);    //Add line and line number to map
         linenumber++;                     //Increment line number
    }

    return poemmap;
}

此函数将从 List 中生成一个 HashMap 并返回它。get()当需要写入文件时,可以使用 HashMap 函数检索这些行。


推荐阅读