仅将文件中的特定文本添加到数组列表 [英] Adding only specific text from a file to an array list
问题描述
我希望我能在这里得到一些帮助.
I hope I can get here some help.
这是我文件中的文本:
Name: John
Name: Peter
Name: Sarah
Place: New York
Place: London
Place: Hongkong
例如,我如何仅在以下数组列表中添加文本文件中的名称?到目前为止,我已经......并且它添加了数组列表中的所有内容,包括位置!
How can I for example only add the names from the text file in the following arraylist? So far, I've got... and it add everything in the arraylist, including places!
private ArrayList<Name> names = new ArrayList<>();
public void load(String fileName) throws FileNotFoundException {
String text;
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
while((text = input.readLine()) != null){
text = text.replaceAll("Name:", "");
names.add(new Name(text));
}
}
catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
最后,它应该只添加 Name ArrayLIst 中的名称,例如 John、Peter、Sarah.
At the end, it should only add the names in the Name ArrayLIst, like John, Peter, Sarah.
如果您有任何建议,我将不胜感激,谢谢!
I would appreciate for any suggestions, thanks!
推荐答案
添加 if 语句并查找带有Place"的字符串,使用正则表达式并将其删除.这是最简单的方法.
Add an if statement and look for strings with "Place", using a regex expression and knock this out. That is the easiest way.
但这是另一个简单的解决方案.您还可以添加更多单词以注意在 if 中使用 OR 运算符.
But here is another simple solution. You can also add more words to look out for using the OR operator inside the if.
while((text = input.readLine()) != null){
//gets rid of places
if !(a.contains("Place")){
text = text.replaceAll("Name:", "");
names.add(new Name(text));
}
}
这篇关于仅将文件中的特定文本添加到数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!