This question already has an answer here:
这个问题在这里已有答案:
- Reading a plain text file in Java 25 answers
用Java 25答案读取纯文本文件
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)
我想逐行读取并在第一个空格处拆分并将其存储在集合或映射或任何类似的java集合中。 (键和值对)
example :-"apple fruit"
should be stored in a map where the key = apple
and value = fruit
.
例如: - “apple fruit”应该存储在key = apple和value = fruit的地图中。
3 个解决方案
#1
1
The Scanner class is probably what you're after.
Scanner类可能就是你所追求的。
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
0
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
0
Since java 8 you can just do
从java 8开始你就可以做到
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()
如果你想要一个地图,你可以用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)));
#1
1
The Scanner class is probably what you're after.
Scanner类可能就是你所追求的。
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
0
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
0
Since java 8 you can just do
从java 8开始你就可以做到
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()
如果你想要一个地图,你可以用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)));