码迷,mamicode.com
首页 > 其他好文 > 详细

使用univocity-parsers创建和读取csv文件

时间:2015-10-13 11:59:13      阅读:831      评论:0      收藏:0      [点我收藏+]

标签:

import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import com.univocity.parsers.csv.CsvWriter;
import com.univocity.parsers.csv.CsvWriterSettings;

创建csv文件:

public static void createCSVFile(String[] heads, List<Object[]> rows, String outPutPath, String filename)
    {

        // CsvWriter (and all other file writers) work with an instance of
        // java.io.Writer
        File csvFile = new File(outPutPath + filename + ".csv");
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists())
        {
            parent.mkdirs();
        }
        try
        {
            csvFile.createNewFile();
            Writer fileWriter = new FileWriter(csvFile);

            // By default, only values that contain a field separator are enclosed within quotes.
            // If quotes are part of the value, they are escaped automatically as well. Empty rows are discarded automatically.
            // Set the field delimiter to ‘;‘, the default value is ‘,‘
            CsvWriterSettings settings = new CsvWriterSettings();
            CsvFormat format = settings.getFormat();
            format.setDelimiter(‘;‘);

            CsvWriter writer = new CsvWriter(fileWriter, settings);

            // Write the record headers of this file
            writer.writeHeaders(heads);

            // Write contents and close the given output Writer instance.
            writer.writeRowsAndClose(rows);
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error(e);
        }
    }

 

读取csv文件:

public static List<MyType> ReadCSV(String filePath) throws IOException {
        List<MyType> eslImports = new ArrayList<MyType>();

        File file = new File(filePath);
        InputStream in = new FileInputStream(file);
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");

        CsvParserSettings settings = new CsvParserSettings();
        settings.getFormat().setLineSeparator("\n");

        CsvParser parser = new CsvParser(settings);
        //读取数据到列表
        List<String[]> allRows = parser.parseAll(reader);

        //处理读取到的数据

       .....

}

使用univocity-parsers创建和读取csv文件

标签:

原文地址:http://www.cnblogs.com/xiaxinhaha/p/4873996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!