All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.rrsunhome.excelsql.util.CSVUtils Maven / Gradle / Ivy

There is a newer version: 2.1.2
Show newest version
package com.github.rrsunhome.excelsql.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author wanqijia
 */
public class CSVUtils {

    public static  List read(InputStream is, CSVRowMapper csvRw) throws Exception {

        List csvList = new ArrayList<>();
        CsvReader reader = null;
        try {
            reader = new CsvReader(is, StandardCharsets.UTF_8);
            reader.readHeaders();
            int index = 0;
            while (reader.readRecord()) {
                T row = csvRw.mapRow(new CSVResultSet(reader), index);
                if (row == null) {
                    continue;
                }
                csvList.add(row);
                index++;
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return csvList;
    }


    public static File createCsv(String path, String[] head, List dataList) {
        CsvWriter csvWriter = null;
        try {
            csvWriter = new CsvWriter(path, ',', StandardCharsets.UTF_8);
            csvWriter.writeRecord(head);
            for (String[] row : dataList) {
                csvWriter.writeRecord(row);
            }
            return new File(path);

        } catch (Exception e) {

            throw new RuntimeException("create csv ex", e);
        } finally {
            if (csvWriter != null) {
                csvWriter.close();
            }
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy