简体   繁体   中英

Write text file content into custom arraylist in Java

Suppose I have a text file DataBase.txt with the following content:

1    leo               messi              12.12.1986
2    cristiano         ronaldo            22.01.1985
3    arjen             robben             14.11.1991

And a custom arraylist which looks like this:

public static ArrayList<Rows> InfoList = new ArrayList<Rows>();

This is my Rows class implementation with setters, getters and toString method:

public class Rows {

    public int id;
    public String firstName;
    public String secondName;
    public String dateOfbrth;

    @Override
    public String toString() {
        return this.id + "      " + this.firstName + "      " + 
                this.secondName + "      " + this.dateOfbrth;
    }

    public int getId() {
        return id;
    }
    public String getFirstName() {
        return firstName;
    }
    public String getSecondName() {
        return secondName;
    }
    public String getDateOfbrth() {
        return dateOfbrth;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public void setSecondName(String secondName) {
        this.secondName = secondName;
    }
    public void setDateOfbrth(String dateOfbrth) {
        this.dateOfbrth = dateOfbrth;
    }
}

So. the question is: How to write text file content into an arrayList where every element will be refered to its own field in class Rows. despite of different count of spaces in each line ? Which algorithms or Java classes will be useful to approach that ?

I'm novice in Java so I tried to do this using BuffredReader but I stuck with separating line and adding each element into arrayList :

try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
    for (String line; (line = br.readLine()) != null; ) {

    }
}

Thanks for any help

This is the way:

try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
    String line;
    while((line = br.readLine())!=null ) {
        String[] values = line.split("\\s+");
        ...
    }
}
    while ((line = br.readLine()) != null) {
            String[] row = line.split("\\s+");
            Row row = new Row();
            row.setId(row[0]);
            row.setFirstName(row[1]);
            row.setSecondName(row[2]);
            row.setDateOfbrth(row[3]);
            InfoList.add(row);
        }

\\s+ is a regex expression which will cause any number of consecutive spaces to split your string into tokens, see this answer How to split a String by space Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM