Parse and read data from a text file [duplicate]

廉价感情. 提交于 2019-12-03 00:01:44

问题


I have data in my text file in the following format

apple fruit
carrot vegetable
potato vegetable 

I want to read this line by line and split at the first space and store it in a set or map or any similar collections of java. (key and value pairs)

example :-
"apple fruit" should be stored in a map where the key = apple and value = fruit.


回答1:


The Scanner class is probably what you're after.

As an example:

 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:


You can do something like this:

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:


Since java 8 you can just do

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

if you want a map, you can just replace the Collectors.toSet by 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)));


来源:https://stackoverflow.com/questions/42258936/parse-and-read-data-from-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!