从文本文件中解析和读取数据

时间:2017-02-15 20:02:11

标签: java parsing set filereader

我的文本文件中的数据格式如下

apple fruit
carrot vegetable
potato vegetable 

我希望逐行读取并在第一个空格处拆分并将其存储在集合或映射或任何类似的java集合中。 (键和值对)

例子: -
"apple fruit" 应该存储在地图中 key = applevalue = fruit

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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
}

答案 2 :(得分: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)));