使用UNIVOCITY-PARSERS创建和读取CSV文件

本文介绍如何使用UNIVOCITY-PARSERS库在Java中创建和读取CSV文件,详细解析了配置与使用方法,帮助开发者高效地操作CSV数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

        //处理读取到的数据

       .....

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值