Adding only specific text from a file to an array list [duplicate]

南楼画角 提交于 2019-12-13 06:04:20

问题


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

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