user3191018
user3191018

Reputation: 9

Java Read Each Line Into Separate ArrayList (String)

Is it posible to put eachline (from txt file) to sepperate arraylist etc and put them incide Array DATABASE

I have a file with info of students something like that

Name Lastname yearsOld address BEN DDD 12 14Drive Olga Benar 12 23Ave

So in result I would have an ArrayLIST with arraylist(of each student)?

Upvotes: 0

Views: 976

Answers (1)

ssnielsen
ssnielsen

Reputation: 547

How about creating a model of your data? E.g:

class Student {
    String name;
    String lastname;
    int yearsOld;
    ...more fields...
}

And use that to load your data into an ArrayList<Student>.

EDIT: However, to answer your question. Use the IO library to read the file line by line:

public List<List<String>> processFile(String file) throws IOException {      
    List<List<String>> data = new ArrayList<List<String>>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
       data.add(processLine(line));
    }
    br.close();
    return data;
}

public List<String> processLine(String line) {
    return Arrays.asList(line.split(" ")); //  Be aware of spaces in names, addresses etc.
}

Upvotes: 1

Related Questions