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

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

apple fruit carrot vegetable potato vegetable 

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

例如: –
"apple fruit"应该存储在key = applevalue = fruit的地图中。

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

你可以这样做:

 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 } 

从java 8开始你就可以做到

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

如果你想要一个地图,你可以用Collectors.toMap()替换Collectors.toSet

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