Java从文件中读取并放入地图

时间:2017-10-17 20:38:34

标签: java

你好我在某个文件夹中有很多文件txt,每个文件txt都有相同的结构:

Name Surname
Date of Birth
titles works of authors

像:

Wolfgang Amadeus Mozart

1756 w Salzburgu

Requiem d-moll 

ave verum corpus

lacrymosa
piano sonata no. 16
etc.

我想创建HashMap:

  • Key是作者
  • 值是有效的

在我的程序中,我不需要出生名,但我不能从txt中删除这一行。

到目前为止我写了那段代码:

  public void check() throws IOException {

    Finder finder = new Finder();
    File[] files = finder.findTxtFiles("folder");

    Map<String, List<String>> painters = new HashMap<String, List<String>>();
    List<String> titles = new ArrayList<>();

    for(File file : files){
        BufferedReader bufferedReader = Files.newBufferedReader(Paths.get(file.getPath()), StandardCharsets.ISO_8859_1);
        String painterName = bufferedReader.readLine();
        bufferedReader.readLine();

        while(bufferedReader.readLine() != null) {
            titles.add(bufferedReader.readLine());
        }
        painters.put(painterName,titles);
    }
}

public class Finder {

    public static File[] findTxtFiles(String dirName){
        File file = new File(dirName);
        return file.listFiles((dir1, filename) -> filename.endsWith(".txt"));
    }

}

我有列表的问题,因为我添加到列表中的所有值,不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要为每个键添加一个新列表,因此请在for循环中创建列表。

library(tidyverse)
df %>% 
    group_by(Row) %>% 
    mutate(id = row_number()) %>% 
    spread(key = Row, value = People) %>% 
    select(-id)