简体   繁体   中英

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)?

How about creating a model of your data? Eg:

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.
}

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