2017-10-17 46 views
-4

你好,我有很多在某个文件夹的txt文件,每个文件TXT具有相同的结构:的Java读取,并把映射

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:

  • 重点是笔者
  • 值是作品

在我的程序中我不需要出生的名字,但我不能从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")); 
    } 

} 

我有问题清单,becouse我添加到地图,从列表中的所有值,不知道如何解决这个问题。

+2

而你的问题是... –

+0

在这种情况下有一个列表,我需要不同的密钥 –

+0

[“我需要* X *”是不是一个问题(HTTP每个不同的列表://元.stackoverflow.com/q/284236)。请[编辑]你的问题,以更具体地了解你需要什么。 –

回答

0

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

public void check() throws IOException { 

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

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


    for(File file : files){ 
     List<String> titles = new ArrayList<>(); 

     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); 
    } 
}