[英]How to read a list from a text file in java
I am trying to read data from a text file which has multiple lines, for example, look the image below, it is my text file 我正在尝试从具有多行的文本文件中读取数据,例如,看下面的图片,这是我的文本文件
Given a keyword from the user which is the first string in the list from the text file. 给定用户关键字,该关键字是文本文件列表中的第一个字符串。 I want to print the list or line corresponding to the keyword given.
我想打印与给定关键字相对应的列表或行。 For example, if I am giving the keyword=59d2211ec3671594c987d008f89f043e97670a5ba6f08fe073e465116c35b440
例如,如果我给关键字= 59d2211ec3671594c987d008f89f043e97670a5ba6f08fe073e465116c35b440
Then I want to store [59d2211ec3671594c987d008f89f043e97670a5ba6f08fe073e465116c35b440, id4, id6, id1] as a list. 然后,我想将[59d2211ec3671594c987d008f89f043e97670a5ba6f08fe073e465116c35b440,id4,id6,id1]存储为列表。
I have tried using the following function to read the text file and return the data but it's giving me some wrong input. 我尝试使用以下功能读取文本文件并返回数据,但这给了我一些错误的输入。
public static List<String> readLines(File file) throws Exception {
if (!file.exists()) {
return new ArrayList<String>();
}
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> results = new ArrayList<String>();
String line = reader.readLine();
while (line != null) {
results.add(line);
line = reader.readLine();
}
return results;
}
Can someone guide me through on how to implement this in a right way. 有人可以指导我完成正确的方法。
if I am giving the keyword
如果我给关键字
Well, if you're given a value, then you should be using it 好吧,如果您得到一个值,那么您应该使用它
readLines(File file, String keyword)
store as a list
储存为清单
Now, I assume you mean split the line into columns. 现在,我假设您的意思是将行分成几列。 If that's the case, you need to be returning at least a
List<List<String>>
如果是这种情况,则需要至少返回一个
List<List<String>>
However, if not, you can do that later than collecting the lines containing the keyword like so 但是,如果不是这样,则可以比收集包含关键字的行晚一些,例如
List<String> results = new ArrayList<String>();
String line = reader.readLine();
while (line != null) {
if (line.contains(keyword)) results.add(line);
line = reader.readLine();
}
return results;
FWIW, I would suggest having a look at Java 8 stream functions, including filter
, map
, and toList
FWIW,我建议您看一下Java 8流函数,包括
filter
, map
和toList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.