0

I am making a program that has an array of people. The people have different amounts of info for instance they all have a first name, last name, type, gender. The first issue I have is some also have email and some have a image (using Icon) and some have both of them.

I need to read these pieces of data in and then display them, it is for a college class and the teacher was basically like figure it out.. I have read the API and numerous articles and can't seem to get it to work. Can someone give me a push in the right direction?

I am not looking for you to hand me the answers just a little help.

4
  • 1
    Consider adding a sample file and code Commented Jan 29, 2014 at 2:08
  • Hint: if you know how to read a file one line at a time, just read each line one at a time. It's a flat file with commas between the fields, and if you are skipping a field, you just have two commas in a row. Then use split to split the line on the commas, so that you have an array. Commented Jan 29, 2014 at 2:09
  • So basically read each line as a string and then split it at the commas? Commented Jan 29, 2014 at 2:42
  • Also I was trying this so far... MemberInterface[] members; String memberList = "members.csv"; File theFile = new File(memberList); Scanner input = new Scanner(theFile); input.useDelimiter(","); Commented Jan 29, 2014 at 2:48

1 Answer 1

1

Read the file line by line and split line with ,. // you need to create a pojo to hold all the user info.

List<UserObject> users = new ArrayList<UserObject>();
try {
    br = new BufferedReader(new FileReader(csvFile));
    while ((line = br.readLine()) != null) {
         String[] userinfos = line.split(",");
         UserObject newUser = new UserObject();
         //set the mandatory attributes here 
         if (userinfos.length > 4) {
             // you have the extra fields here.
             // set the extra fields to user here
         }
         users.add(newUser);
    }

} catch (FileNotFoundException e) {
     e.printStackTrace();
}

One problem with this is first name or last name might have commas with in them. I suggest you to use any third party csv parser like Open Csv.

Sign up to request clarification or add additional context in comments.

2 Comments

There are ways within Java's api to do all the things I need, I would rather use the API or other ways within java to get this task accomplished. Thank you for the reply!
Yes, apart from opencsv suggestion, whole method is using only Java API.