Example usage for org.apache.commons.csv CSVFormat DEFAULT

List of usage examples for org.apache.commons.csv CSVFormat DEFAULT

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat DEFAULT.

Prototype

CSVFormat DEFAULT

To view the source code for org.apache.commons.csv CSVFormat DEFAULT.

Click Source Link

Document

Standard comma separated format, as for #RFC4180 but allowing empty lines.

Usage

From source file:assignment.CSVFileReader.java

@Override
public List<Map<String, String>> readFile(String filePath) {
    Reader reader;/*  w ww  . ja v  a 2s.co  m*/
    List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);

        Iterator<CSVRecord> csvRecord = csvParser.iterator();
        CSVRecord headers = csvRecord.next();

        for (CSVRecord row : csvParser) {
            Map<String, String> item = new HashMap<String, String>();

            int colNr = 0;
            for (String header : headers) {
                String r = "";
                try {
                    r = row.get(colNr);
                } catch (Exception ex) {

                }
                item.put(header, r);
                colNr++;
            }
            rows.add(item);
        }
    } catch (Exception ex) {

    }
    return rows;
}

From source file:com.github.douglasjunior.japriori.datatarget.CSVDataTarget.java

public CSVDataTarget(File file, char delimiter, Charset charset) throws IOException {
    this.file = file;
    this.charset = charset;
    this.csvFormat = CSVFormat.DEFAULT.withDelimiter(delimiter).withIgnoreEmptyLines().withEscape('\\')
            .withQuoteMode(QuoteMode.NONE).withSkipHeaderRecord();
    open();/*from  w  w w .j a v  a  2 s .  c  o  m*/
}

From source file:com.kircherelectronics.gyroscopeexplorer.datalogger.CsvDataLogger.java

public CsvDataLogger(Context context, File file) {
    this.context = context;
    this.file = file;

    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));

    try {/*w ww  .  j  av  a 2s .com*/
        fileWriter = new FileWriter(file);
        csv = new CSVPrinter(fileWriter, csvFileFormat);
    } catch (IOException e) {
        e.printStackTrace();
    }

    headersSet = false;
}

From source file:de.dhbw.vetaraus.CSV.java

/**
 * Create a list of Case objects from a given filepath. The filepath must be a CSV file with semicolon-delimited
 * entries. The first line of the file (header record) will be ignored.
 * <p>/*w  w w. j a  v a2 s.  co  m*/
 * Each line of the file must have the following values:
 * ID, age, gender, married, children, degree, occupation, income, tariff.
 *
 * @param path
 *         Path to the CSV file.
 * @return a list of Case objects from the given input file.
 * @throws IOException
 */
public static List<Case> parse(String path) throws IOException {
    try (FileInputStream fis = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader file = new BufferedReader(isr)) {

        final CSVParser parser = new CSVParser(file,
                CSVFormat.DEFAULT.withDelimiter(';')
                        .withHeader(Constants.HEADER_NUMBER, Constants.HEADER_AGE, Constants.HEADER_GENDER,
                                Constants.HEADER_MARRIED, Constants.HEADER_CHILDREN, Constants.HEADER_DEGREE,
                                Constants.HEADER_OCCUPATION, Constants.HEADER_INCOME, Constants.HEADER_TARIFF)
                        .withSkipHeaderRecord(true));

        return parser.getRecords().stream()
                .map(record -> new Case(record.get(Constants.HEADER_NUMBER), record.get(Constants.HEADER_AGE),
                        record.get(Constants.HEADER_GENDER), record.get(Constants.HEADER_MARRIED),
                        record.get(Constants.HEADER_CHILDREN), record.get(Constants.HEADER_DEGREE),
                        record.get(Constants.HEADER_OCCUPATION), record.get(Constants.HEADER_INCOME),
                        record.get(Constants.HEADER_TARIFF)))
                .collect(Collectors.toList());
    }
}

From source file:com.teamnx.util.CSVToDateBase.java

/**
 * @param fileName/*from   www  .ja  v  a2 s .  c  o  m*/
 * @param type
 * @return
 */
public List readCsvFile(String fileName, int type) {
    FileReader fileReader = null;
    CSVParser csvFileParser = null;
    List list = null;
    //CSVFormatheader mapping
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(file_header);
    try {
        //?FileReader object
        fileReader = new FileReader(fileName);
        //? CSVParser object
        csvFileParser = new CSVParser(fileReader, csvFileFormat);
        //CSVrecords
        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        // CSV

        switch (type) {
        case USER:
            List<User> userList = new ArrayList<User>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                User user = new User();
                user.setId(record.get("id"));
                user.setName(record.get("name"));
                user.setPassword(record.get("password"));
                user.setDepartment_id(Integer.parseInt(record.get("department_id")));
                user.setCharacter(Integer.parseInt(record.get("character")));
                user.setClass_id(record.get("class_id"));
                user.setDepartment_name(record.get("department_name"));
                userList.add(user);
            }
            list = userList;
            break;
        case DEPARTMENT:
            List<Department> departmentList = new ArrayList<Department>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                Department department = new Department();
                department.setId(Integer.parseInt(record.get("id")));
                department.setName(record.get("name"));
                departmentList.add(department);
            }
            list = departmentList;
            break;
        case COURSE:
            List<Course> courseList = new ArrayList<Course>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                Course course = new Course();
                course.setId(record.get("id"));
                course.setName(record.get("name"));
                course.setDepartment_id(Integer.parseInt(record.get("department_id")));
                course.setStart_time(Integer.parseInt(record.get("start_time")));
                course.setEnd_time(Integer.parseInt(record.get("end_time")));
                course.setPosition(record.get("position"));
                course.setSchedule(record.get("schedule"));
                course.setYear(Integer.parseInt(record.get("year")));
                course.setSemester(Integer.parseInt(record.get("semester")));
                int j = Integer.parseInt(record.get("category"));
                course.setCategory(j == 1 ? true : false);
                course.setMax_member(Integer.parseInt(record.get("max_member")));
                courseList.add(course);
            }
            list = courseList;
            break;
        case STUDENT_COURSE:
            List<StudentCourse> studentCourseList = new ArrayList<StudentCourse>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                StudentCourse studentCourse = new StudentCourse();
                studentCourse.setId(record.get("id"));
                studentCourse.setCourseId(record.get("course_id"));
                studentCourse.setStudentId(record.get("student_id"));
                studentCourseList.add(studentCourse);
            }
            list = studentCourseList;
            break;
        case TEACHER_COURSE:
            List<TeacherCourse> teacherCourseList = new ArrayList<TeacherCourse>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                TeacherCourse teacherCourse = new TeacherCourse();
                teacherCourse.setId(record.get("id"));
                teacherCourse.setTeacherId(record.get("teacher_id"));
                teacherCourse.setCourseId(record.get("course_id"));
                teacherCourseList.add(teacherCourse);
            }
            list = teacherCourseList;
            break;

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
            csvFileParser.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return list;
        }
    }
}

From source file:com.linkedin.pinot.core.data.readers.CSVRecordReaderTest.java

@BeforeClass
public void setUp() throws Exception {
    FileUtils.forceMkdir(TEMP_DIR);// ww  w  . j av a  2  s  .  c  om

    try (FileWriter fileWriter = new FileWriter(DATA_FILE);
            CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(COLUMNS))) {
        for (Object[] record : RECORDS) {
            csvPrinter.printRecord(record[0],
                    StringUtils.join((int[]) record[1], CSVRecordReaderConfig.DEFAULT_MULTI_VALUE_DELIMITER));
        }
    }
}

From source file:com.intropro.prairie.format.sv.SvFormatWriter.java

@Override
public void write(Map<String, Object> line) throws IOException {
    if (csvPrinter == null) {
        headers = line.keySet().toArray(new String[line.size()]);
        csvPrinter = CSVFormat.DEFAULT.withDelimiter(delimiter).withHeader(headers).print(writer);
    }/*w  w w .  ja v a 2s. c  om*/
    Object[] values = new Object[headers.length];
    for (int i = 0; i < headers.length; i++) {
        values[i] = line.get(headers[i]);
    }
    csvPrinter.printRecord(values);
}

From source file:com.intropro.prairie.format.sv.SvFormatReader.java

@Override
public Map<String, Object> next() throws IOException {
    if (csvParser == null) {
        csvParser = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter).parse(inputStream);
        iterator = csvParser.iterator();
    }// ww w.j  a  va 2 s  . c  o m
    if (!iterator.hasNext()) {
        return null;
    }
    CSVRecord csvRecord = iterator.next();
    return new HashMap<String, Object>(csvRecord.toMap());
}

From source file:com.denimgroup.threadfix.csv2ssl.parser.CSVToSSVLParser.java

public static String parseCsv(File file, String... format) {
    try {/* www .  j av a 2s  .c om*/
        CSVParser parse = CSVFormat.DEFAULT.withSkipHeaderRecord(CONFIG.shouldSkipFirstLine).withHeader(format)
                .parse(new FileReader(file));

        return RecordToXMLSerializer.getFromReader(parse);
    } catch (IOException e) {
        throw new IllegalStateException("Received IOException while parsing file.", e);
    }
}

From source file:edu.caltech.ipac.firefly.server.util.DsvToDataGroup.java

public static void write(File outf, DataGroup data) throws IOException {
    write(new FileWriter(outf), data, CSVFormat.DEFAULT);
}