2017-02-15 79 views
-1

我在文本文件中的數據採用以下格式讀取數據解析和從文本文件

apple fruit 
carrot vegetable 
potato vegetable 

我想在第一空間讀取此一行一行地分開,並將其存儲在一組或地圖或任何類似的Java集合。 (鍵和值對)

例如: -
"apple fruit" 應被存儲在地圖其中 key = applevalue = fruit

+0

你好,歡迎來到SO。看起來你沒有花太多時間研究這個話題,否則你會發現一堆例子。如果您仍然認爲您需要社區的幫助,請提供您自己的解決方案的代碼,我們可以討論並提出改進建議。有人不太可能樂意爲你完成全部任務。 –

回答

1

Scanner類可能是你在追求的。

舉個例子:

Scanner sc = new Scanner(new File("your_input.txt")); 
while (sc.hasNextLine()) { 
    String line = sc.nextLine(); 
    // do whatever you need with current line 
} 
sc.close(); 
0

你可以做這樣的事情:

BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
String currentLine; 
while ((currentLine = br.readLine()) != null) { 
    String[] strArgs = currentLine.split(" "); 
    //Use HashMap to enter key Value pair. 
    //You may to use fruit vegetable as key rather than other way around 
} 
0

由於Java 8,你可以做

Set<String[]> collect = Files.lines(Paths.get("/Users/me/file.txt")) 
      .map(line -> line.split(" ", 2)) 
      .collect(Collectors.toSet()); 

如果你想有一個地圖,你可以用Collectors.toMap替換Collectors.toSet()

Map<String, String> result = Files.lines(Paths.get("/Users/me/file.txt")) 
      .map(line -> line.split(" ", 2)) 
      .map(Arrays::asList) 
      .collect(Collectors.toMap(list -> list.get(0), list -> list.get(1)));