问题
I hope I can get here some help.
This is the text in my file:
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());
}
}
At the end, it should only add the names in the Name ArrayLIst, like John, Peter, Sarah.
I would appreciate for any suggestions, thanks!
回答1:
Add an if statement and look for strings with "Place", using a regex expression and knock this out. That is the easiest way.
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));
}
}
回答2:
Try Splitting each line you have on the delimiter :, for instance:
String[] parts = text.split(":");
String part1 = parts[0]; // Name
String part2 = parts[1]; // John
来源:https://stackoverflow.com/questions/16050851/adding-only-specific-text-from-a-file-to-an-array-list