2017-02-15 45 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)));