【问题标题】:Parse and read data from a text file [duplicate]从文本文件中解析和读取数据[重复]
【发布时间】:2017-07-04 16:16:21
【问题描述】:

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

apple fruit
carrot vegetable
potato vegetable 

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

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

【问题讨论】:

  • 您好,欢迎来到 SO。看起来你没有花太多时间研究这个主题,否则你会找到一堆例子。如果您仍然认为需要社区的帮助,请提供您自己的解决方案代码,我们可以讨论并提出改进建议。不太可能有人会乐意为您完成任务。

标签: java parsing set filereader


【解决方案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(); 

【讨论】:

    【解决方案2】:

    你可以这样做:

    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
    }
    

    【讨论】:

      【解决方案3】:

      从 java 8 开始你就可以做

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

      如果你想要一张地图,你可以把 Collectors.toSet 替换为 Collectors.toMap()

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

      【讨论】:

        猜你喜欢
        • 2016-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多