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

Java 从文本文件中解析和读取数据,java,parsing,set,filereader,Java,Parsing,Set,Filereader,我的文本文件中有以下格式的数据 apple fruit carrot vegetable potato vegetable 我想逐行阅读这篇文章,并在第一个空格处拆分,然后将其存储在一个集合、地图或任何类似的java集合中。(键和值对) 示例:- “苹果水果” 应存储在 key=apple和 value=fruit这门课可能就是你想要的 例如: Scanner sc = new Scanner(new File("your_input.txt")); while (sc.hasNextL

我的文本文件中有以下格式的数据

apple fruit
carrot vegetable
potato vegetable 
我想逐行阅读这篇文章,并在第一个空格处拆分,然后将其存储在一个集合、地图或任何类似的java集合中。(键和值对)

示例:-
“苹果水果”
应存储在
key=apple
value=fruit

这门课可能就是你想要的

例如:

 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
}

由于Java8,您只需

Set<String[]> collect = Files.lines(Paths.get("/Users/me/file.txt"))
            .map(line -> line.split(" ", 2))
            .collect(Collectors.toSet());
Set collect=Files.line(path.get(“/Users/me/file.txt”))
.map(直线->直线分割(“,2))
.collect(收集器.toSet());
如果需要映射,只需将Collectors.toSet替换为Collectors.toMap()

Map result=Files.line(path.get(“/Users/me/file.txt”))
.map(直线->直线分割(“,2))
.map(数组::asList)
.collect(Collectors.toMap(list->list.get(0),list->list.get(1));

您好,欢迎来到SO。看起来你并没有在这方面投入太多的时间,否则你会发现很多例子。如果您仍然认为您需要社区的帮助,请提供您自己的解决方案代码,我们可以讨论并提出改进建议。不太可能有人愿意为你完成这项任务。
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)));