2017-10-17 29 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); 
    } 
}