如何制作动态的对象列表

时间:2014-09-11 13:51:49

标签: java object string-parsing opencsv

假设我有一个CSV文件:

employees.csv

ID,Name,Role,Salary
1,Pankaj Kumar,CEO,"5,000USD"
2,Lisa,Manager,500USD
3,David,,1000USD

我可以将其解析为Employee对象列表:

Employee.java

package com.journaldev.parser.csv;

public class Employee {

    private String id;
    private String name;
    private String role;
    private String salary;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getSalary() {
        return salary;
    }
    public void setSalary(String salary) {
        this.salary = salary;
    }

    @Override
    public String toString(){
        return "ID="+id+",Name="+name+",Role="+role+",Salary="+salary+"\n";
    }
}

但是如果我想创建我的代码以便它可以处理具有更多或更少列的文件,而不事先知道它们的名称是什么呢?

employees.csv

ID,Name,Role,Salary, dateJoined, sex
1,Pankaj Kumar,CEO,"5,000USD",Jan 05 2014 12:04:01PM,MALE
2,Lisa,Manager,500USD,Feb 11 2012 12:04:01PM, FEMALE
3,David,,1000USD,Jan 02 2013 12:04:01PM, MALE

我想这样做,以便与文件中的列数无关。 因此,对于文件中的每一列,代码都会在对象列表中创建另一个元素。

我的其余代码:

package openCSV_fileReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class OpenCSV_fileReader {

     public static void main(String[] args) throws IOException {

            List<Employee> emps = parseCSVFileAsList();
            System.out.println("**********");
            writeCSVData(emps);
     }
        private static void writeCSVData(List<Employee> emps) throws IOException {
            StringWriter writer = new StringWriter();
            CSVWriter csvWriter = new CSVWriter(writer,'#');
            List<String[]> data  = toStringArray(emps);
            csvWriter.writeAll(data);
            csvWriter.close();
            System.out.println(writer);
        }

        private static List<String[]> toStringArray(List<Employee> emps) {
            List<String[]> records = new ArrayList<String[]>();
            //add header record
            records.add(new String[]{"ID","Name","Role","Salary"});
            Iterator<Employee> it = emps.iterator();
            while(it.hasNext()){
                Employee emp = it.next();
                records.add(new String[]{emp.getId(),emp.getName(),emp.getRole(),emp.getSalary()});
            }
            return records;
        }

        private static List<Employee> parseCSVFileAsList() throws IOException {
            CSVReader reader = new CSVReader(new FileReader("employees.csv"), ',');

            List<Employee> emps = new ArrayList<Employee>();
            //read all lines at once
            List<String[]> records = reader.readAll();

            Iterator<String[]> iterator = records.iterator();
            //skip header row
            iterator.next();

            while(iterator.hasNext()){
                String[] record = iterator.next();
                Employee emp = new Employee();
                emp.setId(record[0]);
                emp.setName(record[1]);
                emp.setRole(record[2]);
                emp.setSalary(record[3]);
                emps.add(emp);
            }

            reader.close();

            System.out.println(emps);
            return emps;
        }     
}

这可行吗? 这是我无法找到这样做的方法。

1 个答案:

答案 0 :(得分:1)

public class CSVTable {

    private String[][] csvTable = null;

    public CSVTable(int columns)
    {
        csvTable = new String[columns][2];
    }

    public String[][] getCSVTable()
    {
        return this.csvTable;
    }

    public void setCSVTable(String[][] csvTable)
    {
        this.csvTable = csvTable;
    }
}

private static List<Employee> parseCSVFileAsList() throws IOException {
            CSVReader reader = new CSVReader(new FileReader("employees.csv"), ',');

        List<CSVTable> csvObjects = new ArrayList<CSVTable>();
        //read all lines at once
        List<String[]> records = reader.readAll();
        String[] columns = null;
        String[] record = null;
        int length = 0;
        Iterator<String[]> iterator = records.iterator();
        //skip header row

        record = iterator.next();
        length = record.length;
        columns = new String[length];
        for(int i = 0; i < length; i++)
        {
            columns[i] = record[i];
        }


        while(iterator.hasNext()){
            record = iterator.next();
            CSVTable csvTable = new CSVTable(record.length);
            String[][] insertRecord = csvTable.getCSVTable();
            for(int i = 0; i < length; i++)
            {
                insertRecord[i][0] = columns[i];
                insertRecord[i][1] = record[i];
            }
            csvTable.setCSVTable(insertRecord);
            csvObjects.add(csvTable);
        }

        reader.close();

        System.out.println(csvObjects);
        return csvObjects;
    }

我希望这已经足够了,显然你也必须修改其他一些方法。