This question already has answers here:
Reading a plain text file in Java
                                
                                    (28个答案)
                                
                        
                2年前关闭。
            
        

我创建了一个名为myMap的hashmap>,我想将所有唯一单词存储在Hashmap的键中,并将文件名存储在与关键字对应的值中。
从多个文件中获取输入并将其名称存储在与关键字对应的值中。

来自1个文件的样本输入

AS YOU LIKE IT

by William Shakespeare



DRAMATIS PERSONAE.

DUKE, living in exile
FREDERICK, his brother, and usurper of his dominions
AMIENS, lord attending on the banished Duke
JAQUES,   "      "       "  "     "      "
LE BEAU, a courtier attending upon Frederick
CHARLES, wrestler to Frederick
  OLIVER, son of Sir Rowland de Boys
JAQUES,   "   "  "    "     "  "




String name = f.getName();

    BufferedReader in = new BufferedReader(new FileReader(f));
    String words = in.readLine().trim().toLowerCase();

    for(String word: words.split("\\s+")) {
        if (myMap.get(word) == null) {
            myMap.put(word, new ArrayList<String>());
        }
            myMap.get(word).add(name);
        }


我只能从所有文件中读取第一行。

最佳答案

这是读取所有行的另一种方法:

https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines(java.nio.file.Path,%20java.nio.charset.Charset)

10-05 21:11
查看更多